Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django give permissions to users per company
In my case I have different users which can be part of different companies. An user can belong to multiple companies and a company has multiple customers, products, services, … Now I want the user to be able to have different permissions per company. So let’s say user X can manage the customers in company A but can only read the products and services. And user X can manage the users, products and services in company B. I would like to work with roles: so manage everything would be the role “superadmin” and manage customers but read products and services would be the role “sales” for example. So in short: I want to create roles where I can assing permssions to and then add these roles to users per company. I am planning on using rsinger86/drf-access-policy to manage access control but any suggestions are welcome. Please suggest me a good way to accomplish this scenario. How am I able to add roles per company and am I still able to use the by-default-generated auth_permissions from Django? Thank you in advance! -
{ "product": [ "This field is required."] } in Django REST API
This is my models and I defined set null=True, blank=True for foreign key relations but when I hit my API then API response raised that { "product": [ "This field is required."] }. What I wrote wrong. please help me. **Here is my model:** class CashSell(models.Model): user_profile = models.ForeignKey('accounts.UserProfile', on_delete=models.CASCADE) product = models.ForeignKey('inventory.Product', on_delete=models.CASCADE, related_name='cash_sell', null=True, blank=True) cash_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) description = models.CharField(max_length=250) date = models.DateField() picture = models.ImageField(upload_to='cash_sell_pics', blank=True, null=True, default='images.png') def __str__(self): return self.user_profile.first_name class Meta: verbose_name = "Cash Sell" verbose_name_plural = "Cash Sell" -
How to design django app with integrated gRPC server?
I am currently working on a django project where I need a separate backend application to be able to initiate gRPC requests to my django frontend. Simply put: I want the backend to be able to access and change objects. Therefore I need my django project to also start my grpc server while starting up. I did a lot of research and didn't really find any best practice on that. As far as I would imagine, I could override the startup command of django to also start my grpc server on a seperate thread. But I am afraid that I will end up with a very bad practice solution. Is there any recommendable way to do this? I am excited about every hint :) -
How to query all the fields in parent as well as child model related with a foreign key in Django ? where id matches to the parent class?
I have 3 models in this project class products(models.Model): product_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=True, null=True) userslikedproduct = models.ManyToManyField(UserAccount, blank=True) def __str__(self): return self.product_id class productReviews(models.Model): review_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) product = models.ForeignKey(products, related_name='reviews', on_delete=models.CASCADE) user = models.ForeignKey(UserAccount, related_name='users', on_delete=models.CASCADE) review_desc = models.TextField(blank=True, null=True) review_rating = models.IntegerField(choices=RATING, null=True) date_added = models.DateTimeField(verbose_name='date_added', auto_now_add=True) class ReviewImage(models.Model): review = models.ForeignKey(productReviews, related_name='review_images', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to="/images/") I want to fetch all the reviews related to a product id along with review images. I tried using Query1 = productReviews.objects.all().filter(product=product).values().order_by('-date_added') Query2 = ReviewImage.objects.filter(review__product__product_id=product).values_list('review', 'image') Query1 results in all the objects without images Query2 reults in all the images and review ids without review objects How can I fetch all the reviews of one particular product along with the review images? -
Getting url of image on django/wagtail site
I have a wagtail site - where blogpages are rendered by looping through a streamfield (in which each block can have an image, a heading and some text): <div class="col-md-8 mx-auto px-auto"> <div class="conundrum mb-3">{{ page.category }}</div> <h1>{{ page.title }}</h1> <p class="meta">{{ page.date }}</p> <div class="intro my-4 py-4">{{ page.intro }}</div> {% for block in page.content %} <div class="pb-4"> {% image block.value.image fill-1000x500 class='blog_image' %} <h2 class="py-2 my-2"> {% include_block block.value.heading %} </h2> {% include_block block.value.text %} </div> {% endfor %} </div> I want the 'tweet this' button on the blogpage to include the first image on that page. <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@PsymatikDotCom" /> <meta name="twitter:title" content="{{page.title}}" /> <meta name="twitter:description" content="{{page.intro}}"/> <meta name="twitter:image" content="https://how_do_i_get_this_path" /> But it is not clear to me how to dynamically grab the url of the first image to enter it in the twitter:image section? -
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically. please if anyone can help me out
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically.. please if anyone can help me out with this https://github.com/akj1608/bicaption/runs/5498451909?check_suite_focus=true https://github.com/akj1608/bicaption https://frts.azurewebsites.net/ if anyone can help, please do! -
Why after parsing template ,my modals doesn't work
My reply comment modal doesn't work after I parsed the templates(navigation,footer,base).But if I put them all in same page (not parsing) is working.If I parse them,the modal reply (id="modal-reply") doesnt't work.Can anyone help me?What should I do to fix that? (blablablablablalbblablablablablablablabla) . . . . commentsAdmin.html {% extends 'AdminTemplates/baseAdmin.html' %} {% load static %} {% block contentAdmin %} <div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'indexAdmin' %}">Anasayfa</a> </li> <li class="breadcrumb-item active">Yorumlar</li> </ol> <div class="box_general"> <!-- <div class="header_box"> <h2 class="d-inline-block">Yorumlar</h2> <div class="filter"> <select name="orderby" class="selectbox"> <option value="Any time">Any time</option> <option value="Latest">Latest</option> <option value="Oldest">Oldest</option> </select> </div> </div> --> <div class="list_general reviews"> <ul> <!-- {{stars}} --> {% for comment in comments %} <li> <span>{{comment.created_date}}</span> <span class="rating"> {% for star in comment.getStar %} <i class="fa fa-fw fa-star yellow"></i> {% endfor %} {% for star in comment.getNoneStar %} <i class="fa fa-fw fa-star"></i> {% endfor %} </span> <figure><img src="{{comment.course.image.url}}" alt=""></figure> <h4>{{comment.course.title}}</h4> <p>{{comment.comment}}</p> <p class="inline-popups"><a href="#modal-reply" data-effect="mfp-zoom-in" class="btn_1 gray"><i class="fa fa-fw fa-reply"></i> Reply to this review</a></p> </li> {% endfor %} </ul> </div> </div> </div> <!-- /container-fluid--> </div> {% endblock contentAdmin %} {% block scriptsAdmin %} <!-- Bootstrap core JavaScript--> <script src="{% static 'assetsAdmin/vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'assetsAdmin/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core … -
PageNumberPagination in django via custom queryset
Scenario : I am using django rest framework and I want to create an API to list products using Pagination. Problem: I have a dictionary coming through a defined method (which shows products for a filtered category) and now I want to pass this dictionary to queryset. Is it feasible? class PageNumberSetPagination(PageNumberPagination): page_size = 5 ordering = '-created_at' class ProductList(ListAPIView): queryset = getCategoryProduct() serializer_class = ProductSerializer pagination_class = PageNumberSetPagination In settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } -
Session items wont set on every Cart Item Added
Cart:- class Cart(View): def get(self , request): categories = Category.get_all_categories() if(request.session['cart']): productsToShow = request.session['cart'] else: productsToShow = [] productid = request.GET.get('product') product = get_object_or_404(Products, id=productid) sellername = request.GET.get('seller') seller = get_object_or_404(Sellers, name=sellername) productsToShow = [] prices = Price.objects.filter(product=product,seller=seller) for price in prices: product = price.product product.seller = price.seller product.price = price.cost productsToShow.append(product) request.session['cart'] = productsToShow return render(request , 'cart.html' , {'products' :productsToShow,'categories' : categories} ) AttributeError at /cart 'list' object has no attribute 'keys' -
is it possible to monitor the amount of cryptocurrency in an address on the blockchain app
I was wondering if i could display a counter for both Dogecoin and Bitcoin for my address on my website. You can get images of other websites so I thought this might be possible but I'm not sure. does anyone know if this is possible and if so, how would i do it. -
Html - Create dropdown menu links from logged in user's name
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains more options such as account, myorder, and logout. So I can save space in the navigation bar by avoiding having too many buttons. Some desired examples like below: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will conflict/mess up my current page. CSS <style> .block [for=s1]{ width: 400px; display: block; margin:5px 0; } .block [for=s2]{ width: 800px; display: block; margin:5px 0; } .center [for=s1]{ text-align: center; } .center [for=s2]{ text-align: center; } label[for=s1]{ display: inline-block; width: 100px; text-align: right; } label[for=s2]{ display: inline-block; width: 70px; text-align: left; } input,textarea [for=s1]{ vertical-align: top; } input,textarea [for=s2]{ vertical-align: left; } .page-header { //background-color: #5E5A80; background-color: #454545; margin-top: 0; //padding: 20px 20px 20px 40px; padding: 5px 5px 5px 5px; } .page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } input:focus{ border-color: #66afe9; outline: 0; … -
Django user Follow Unfollow Query
I am creating a Blog post application and one of my requirements is that users can follow and unfollow one another. I have created a profile model class for each user and in that I have added the following column to the user model using a many to many field. People Profile Model -> class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(to=User, related_name='following', blank=True) photo = models.ImageField(upload_to='profile_pics', blank=True,null=True) Phone_number = models.CharField(max_length=255,null=True,blank=True) Birth_Date = models.DateField(null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) Now I am listing all the posts on a webpage and for each post the author is also mentioned on the template. The requirement is that I need to give a button to follow or unfollow the post author. Now for the first time if the user comes on the page on if the author of the post is already followed that I need to show an unfollow button and for this I need to check every post author followings and make changes to my template as per the response from the DB. This is the Query that I have written -> posts = Post.objects.exclude(users=request.user)\ .select_related('user__people','ProductAvailability').prefetch_related('images_set','Likes')\ .annotate(comments_Count = Count('comments_post',distinct=True)).annotate( Count('Likes',distinct=True),is_liked=Exists( Post.Likes.through.objects.filter( post_id=OuterRef('pk'), user_id=user_id ) ),isSaved=Exists( Post.favourites.through.objects.filter( post_id=OuterRef('pk'), user_id=user_id )), … -
DRF - Merge multiple querysets in one ModelViewSet with different models order by time
I am trying to combine three queryset in one which are from different model classes and trying to get json result ordered by time. Each models have time field. I want to merge all of the fields together and want to make a single queryset that can be send to api end point. models.py class DoseRate(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE ,related_name='dose_rates') time = models.DateTimeField(_("Time"), default=timezone.now) cpm = models.IntegerField(_("Counts per minute"), default=0) uSv = models.FloatField(_("Dose rate in uSv"), default=0) time_diff = models.IntegerField(_("Time difference"), default=0) total_counts = models.IntegerField(_("Total counts"), default=0) total_time = models.IntegerField(_("Total time"), default=0) avg_count = models.FloatField(_("Average count"), default=0) std_dev = models.FloatField(_("Standard deviation"), default=0) class GPS(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE ,related_name='gps') uSv = models.FloatField(_("Dose rate in uSv"), default=0) time = models.DateTimeField(_("Time"), default=timezone.now) latitude = models.FloatField(_("Latitude"), default=0) longitude = models.FloatField(_("Longitude"), default=0) address = models.CharField(_("Address"), max_length=200, blank=True, null=True, default=None) class DeviceStatus(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='device_status') time = models.DateTimeField(_("Time"), default=timezone.now) temprature = models.FloatField(_("Temprature"), default=0) frequency = models.IntegerField(_("Frequency"), default=0) voltage = models.FloatField(_("Voltage"), default=0) battery_level = models.IntegerField(_("Battery level"), default=0) serializers.py class AJAXSerializer(serializers.ModelSerializer): class Meta: model = DoseRate # This only provide the data for the avilaible fields fields = ( 'cpm', 'uSv', 'time_diff', 'total_counts', 'total_time', 'avg_count', 'std_dev',) def __init__(self, *args, **kwargs): super(AJAXSerializer, self).__init__(*args, **kwargs) self.request … -
django ORM join statements
I'm learning django queryset API and it's so overwhelming. I'm used to sql statement and I just want a basic join statement where 2 tables join together How can i get this result in shell? SELECT e.emp_lastname,e.emp_firstname,o.job_description FROM hs_hr_employee e INNER JOIN ohrm_job_title o ON e.job_title_code = o.id WHERE e.work_station='101'; hs_hr_employee emp_id,emp_lastname,emp_firstname,work_station,etc... hs_hr_job_title job_id,job_description,etc... -
Need to approve if the user's submitted the request and display the results in the user's page using django rest framework
models.py class Timelog(models.Model): STATUS_CHOICES = [ ('s', 'Submitted'), ('p', 'Approval Pending'), ('a', 'Approved'), ] client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client4',default=None) project=ChainedForeignKey(Project,chained_field="client", chained_model_field="client",show_all=False, auto_choose=True, sort=True) user= models.ForeignKey(User,on_delete=CASCADE,related_name='user2',default=None,blank=True,null=True) job=ChainedForeignKey(Job,chained_field="project", chained_model_field="project",show_all=False, auto_choose=True, sort=True,unique=True) date= models.DateField(default = datetime.date.today) hours=models.DurationField(default=datetime.timedelta(),null=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES,null=False, default='Submitted') class Meta: db_table ='Timelog' def __str__(self): return '{}'.format(self.date) admin.py class Add_Timelog_Admin(admin.ModelAdmin): date_hierarchy = 'date' list_display = ('id','job','project','date','hours','status') list_filter = ['project'] search_fields = ['date'] actions = ['make_approved'] def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id) pass def make_approved(self, request, queryset): queryset.update(status='a') admin.site.register(Timelog, Add_Timelog_Admin) Basically if the user clicks the submitted choice in the status field which will be a button type in the javascript, the status will be shown as submitted in that admin page and it need to shown as approval pending in the users page. Once the admin changes the status to approved it should be shown as approved in users page and it shouldn't be edited by the users after they have submitted it. I have tried using the above code but it seems i couldn't able to acheive the goal. Kindly help to get through this it will be much appreciated, thanks in advance. -
What is the best wat to check if multiple forms in the profile is completely filled or not in Django?
I am working on a project where there are 4 forms and I want to show the profile completed status in percentage. Every form contains fields that are even required=False. Now my question is, how can I get the form is completely filled along the the fields that are not required fields too ? Is their any nice way to do it or just the same that is in my mind.. i.e., to check values individually in views.py using ORM of 4 different Model and then pass parameter to html template ?? -
How to get current user in forms?
I have a form in my Django project. In this form I can assign person. This is my form: class AssignForm(forms.ModelForm): user = forms.ModelChoiceField( queryset=UserProfile.objects.filter(is_active=True) label=_(u'User') ) class Meta: model = Customer fields = ('user',) I want to add another filter in this form. It is company. I get a list of all users in this form but I want to just listing the users that belongs to current user's company. So it should be : queryset=UserProfile.objects.filter(is_active=True, company = current_user.company) But I cannot get requests from forms. How can I handle it? -
Django-filer : specifying the path for the image filer field
I'm using django-filer. All works fine, but it generates a random folder and filename. I want to specify the path by myself. It will be something like this: class ExampleModel(models.Model): image = FilerImageField(null=True, blank=True, on_delete=models.CASCADE, upload_to="myimage/") I know it's not possible to add "upload_to", but is there any method that similar to this? I have read the documentation (https://django-filer.readthedocs.io/en/latest/settings.html#filer-storages), but still do not understand how to do that. Thanks. -
facing problems with 'if' statement for Django templates and Django Models
I have been working on a price comparison site but I am facing a problem when I try to write a if statement for different products so they show their own details rather than showing all detail fields in every product. views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product, Brand, Smartphone_detail def index(request): products = Product.objects.all() return render(request, 'core/home.html', {'products': products}) def categories(request): return { 'categories': Category.objects.all() } def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) return render(request, 'core/products/detail.html', {'product': product}) def category_list(request, category_slug): category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) return render(request, 'core/products/category.html', {'category': category, 'products': products}) models.py from django.db import models from django.urls import reverse from django.db.models import Case, Value, When class Category(models.Model): name = models.CharField(max_length=120, verbose_name='category name') slug = models.SlugField(max_length=150, verbose_name='category url') class Meta: verbose_name_plural = 'categories' def get_absolute_url(self): return reverse("core:category_list", args={self.slug}) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=120, verbose_name='name of the brand') slug = models.SlugField(max_length=120, verbose_name='brand url') image = models.ImageField(upload_to='images/', verbose_name='brand image') description = models.TextField(verbose_name='brand moto or tagline') class Meta: verbose_name_plural = 'brands' def __str__(self): return self.name class Smartphone_detail(models.Model): name = models.CharField(max_length=220, verbose_name=("product name")) brand = models.CharField(max_length=120, verbose_name=("product brand")) ram = models.IntegerField(verbose_name=("ram")) storage = models.IntegerField(verbose_name=("storage")) camera = models.CharField(verbose_name=("camera"), max_length=150) processor = … -
SerializerMethodField not showing all fields of serializer when no FK relationship exists
Desired result I have a nested API response as shown below: { "subject": { "name": "math", "teacher": <uuid>, "teacher_name": "John" }, "grade": 1, } teacher_name is a custom field which uses teacher. It works when subject and grade is set. But when the FK subject is null, I get this response Unwanted result { "subject": { "name": "", "teacher": null, }, "grade": 1, } Question: I would want teacher_name to also appear. I have tried setting it up as a serializers.CharField teacher_name= serializers.CharField( source="teacher.name", read_only=True, allow_blank=True, default=None, ) and a serializers.SerializerMethodField teacher_name= serializers.SerializerMethodField() def get_subject_teacher(self, obj): return obj.teacher.name But to no success. Here is my serializer for the nested API class StudentSerializer(serializers.ModelSerializer): subject = serializers.SerializerMethodField() def get_subject(self, obj): filtered_obj = getattr(obj, "subject", None) return SubjectSerializer(filtered_obj).data class Meta: model = Student fields = ( "subject", "grade", ) class SubjectSerializer(serializers.ModelSerializer): teacher_name= serializers.CharField( source="teacher.name", read_only=True, allow_blank=True, default=None, ) class Meta: model = Subject fields = ( "name", "teacher", "teacher_name", ) -
Get the specific value of filter in Django
I know this is common to ask but I wondered if is there's any way to convert the object value to specific value like Integer , The out put of the filtered query is card_tbl object (1) but I want to get the specific value of this which is 1 cardId = 1 card_tbl = card_tbl.objects.get(id=cardId) print(card_tbl) The Print returns instead of specific value example. 1 card_tbl object (1) Then my second question is there any way to Query the object to another table like this? cardId = 1 card_tbl = card_tbl.objects.get(id=cardId) cat1 = category1_tbl.objects.get(id=card_tbl) Thanks in advance! -
Using Google Tag Manager for Django Sites
I'm running a django site. However, when I use the preview in Google Tag Manager, it does not connect to the server. I need help from other people running the Django site. The preview page exposes the following message. "Could not connect to aaa.com" "A timeout occurred while attempting to connect to https://aaa.com/" And the opened preview page exposes the following message. "Tag Assistant Not Connected error" "Could not connect to Tag Assistant" -
django_auth_adfs: get JWT token for the client on successful authentication
I have a Django application that doesn't have MVC pages and most of the data is served/posted via restful API powered by django-rest-framework. My userbase is in Azure single tenant AD, so I am trying to get the SSO going for them. I am using django_auth_adfs to authenticate users against the Azure AD. Most of the stuff seems to work and the module takes care of the redirects and establishing the Django sessions for the client. Specifying the right permission_classes for the API ViewSets will make sure only authenticated users can access it it works fine via browser with proper django session cookie. What I can't figure out is how to get the JWT token that I can give the UI client so that it could interact with the django-rest-framework API by supplying the JWT bearer and not relying on the session. The documentation is not very specific on these details (besides the password grant that isn't quite relevant for my scenario). -
After applying Auto scale, fail to get object from django restframework model
I deploying Django Restframework API using Github to Azure app service. One of my view get object from django model and show it as json format. It worked well before applying Auto scale. Since my app service uses a lot of CPU, I applied Auto scale. After that it seems my view returned empty json sometimes even though there are records in model. Anyone know why it is happening and how to fix it? -
DRF - Serializers = I want json data for my Parent Child Relationship, How?
I want to create a TreeMenu in my react component so I am using this parent-child relationship - model.py class ProductCategory(models.Model): parent = models.ForeignKey(to='ProductCategory', blank=True, null=True, related_name="sub_cats", on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=False, null=False) desc = models.TextField(blank=True, null=True, db_column='description') def __str__(self): return self.name serializers.py class ParentCategorySerializer(ModelSerializer): parent = serializers.PrimaryKeyRelatedField(required=False, read_only=False, queryset=ProductCategory._default_manager.all()) sub_cats = SubCategorySerializer(many=True, required=False, read_only=False) class Meta: model = ProductCategory fields = ('id', 'parent', 'name', 'desc', 'sub_cats') getting my data as [ { "id":1, "parent":null, "name":"Electronics", "desc":"All kinds of electronics items comes in this category", "sub_cats": [ { "id":2, "name":"Mobiles", "desc":"Category for Smartphones, Features-Phone, etc.", "parent":1 }, { "id":3, "name":"Laptops", "desc":"Category for different - 2 types of laptops.", "parent":1 } ] }, { "id":2, "parent":1, "name":"Mobiles", "desc":"Category for Smartphones, Features-Phone, etc.", "sub_cats":[] }, { "id":3, "parent":1, "name":"Laptops", "desc":"Category for different - 2 types of laptops.", "sub_cats":[] } ] How can i make it better or what need to be done to make a tree menu?