Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Context Processor more than one filter
Im new to Django and python and i have the context processor below but as soon as i try to filter by one than one option it returns an empty queryset? from . models import Job from datetime import date def add_variable_to_context(request): today = date.today() jobs = Job.objects.filter(date_due__lte=today,status='Assigned') overdue = 0 for job in jobs: overdue += 1 return { 'overdue': overdue, 'jobs': jobs, } Can you pass more than one filter in a context processor like you can in a view? -
The value of 'fieldsets[4][1]' must be a dictionary
I user AbstractUser to create my custom account model in Django. Now I have a class in admins.py like so: class CustomAccountAdmin(UserAdmin): model = CustomAccount add_form = CustomAccountCreationForm fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ), ('Other', {'fields': ('phone', 'address', 'description')} ) ) ) admin.site.register(CustomAccount, CustomAccountAdmin) I want to add more fields to my custom account admin and I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'account.admin.CustomAccountAdmin'>: (admin.E010) The value of 'fieldsets[4][1]' must be a dictionary. System check identified 1 issue (0 silenced). This format is working properly but I want to add more: fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ) ) ) -
Though office 365 authenticated my credentials but still not login
I have implemented sign in office 365 integration in my app, though ms office 365 authenticated mt credentials but when it is redirecting it redirects me to the home page and I am still not login into the application any idea?? -
Visualize data from elasticsearch in django app
I'm currently struggling on how to approach this. Currently I have a web application built with django and I have quite some data in elasticsearch. The web app should retrieve data from elastic, process this data and present this data graphically to the user (pie charts, tables, ...). Processing the data from elasticsearch will require some sorting/aggregating/deduplicating/adding up/... . I'm considering the following approaches for now: Get data from elastic via normal queries, process data further in web app using standard python and visualize it using some library (e.g., d3.js). Get data from elastic via normal queries in kibana, visualize data in kibana and integrate visualization in web app (not sure if this is going to work). Get data via elastic eland, convert to pandas data-frame, process data with pandas and visualize data using some library (e.g., d3.js). I'm strongly considering this approach currently. Is one of this approaches a good idea, what would be a better approach? Btw: I have quite some experience in Splunk and with Splunk queries this could be done easily - but Splunk is too expensive for this project :( Thank you! -
django get view method name on permission classes like actions
I have a custom permission like: def has_permission(self, request, view): print("view", view) I am calling list() method of ListModelMixin. Here when I print the value of veiw it gives me class name of the view. But what I want is the name of the method that is being called, in this case list. In view set we can get method name from action attribute. Is there anyway I can get name of the method not the class ?? -
How to apply if else, if the keyword entered in search bar does not exists in Django
I have created a search button in my blogging application that returns the posts with the similar title. views.py has def search(request): query = request.GET.get('query') posts = Post.objects.filter(title__icontains=query).order_by('-date_posted') params = {'posts' : posts} return render(request, 'blog/search.html' , params) base.html <form method="get" class="form-inline my-2my-lg-0 " action="{% url 'search' %}"> <input class="form-control nav-item nav-link text-secondary" type="search" name="query" id="query" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success nav-item nav-link ml-1">Search</button> </form> and search.html {% for post in posts %} <!-- starting loop (posts is keyword from view) --> <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url}}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted | date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id%}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content|slice:":200" }}</p> {% if post.content|length > 200 %} <div class="btn-group-sm"> <a class="btn btn-outline-secondary" href="{% url 'post-detail' post.id%}">Read More &rarr;</a> </div> {% endif %} </div> </article> {% endfor %} Now if the the user enters a keyword that is similar to the title of any post then those posts are returned. If no post title matches that keyword a black page is returned. Instead of a blank page I want a paragraph saying that "no post matches the title " -
Django Debug View, in Production for Admins
I know that settings.DEBUG should be False in production. Nevertheless I would like to show the great django debug view in production, if the current user is authenticated as an admin. I read the Error Reporting Docs, but could not find a setting to turn this on. If it is easier to enable a different debug-view, this would be great, too. At least I want to see a nice stacktrace to understand quickly where the error comes from (without looking at logs). -
Update foreign key in Django rest framework model using viewsets.ModelViewSet view
I am relatively new to DRF and having hard time updating the foreign key in my model via POST request. # Model for Event. class Event(models.Model): heading = models.TextField() event_construction_site = models.ForeignKey( ConstructionSite, on_delete=models.CASCADE, related_name='construction_site_events', null=True) def __str__(self): return str(self.id) class ConstructionSiteShortSerializer(serializers.ModelSerializer): class Meta: model = ConstructionSite fields = ['id'] # Serializer for Event. class EventSerializer(serializers.ModelSerializer): event_construction_site = ConstructionSiteShortSerializer() event_posted_by = CustomUserSerializer() class Meta: model = Event fields = ('id', 'heading', 'event_construction_site') Structure of my GET response is as follows: { id: 1, heading: "Truck with formwork arrived", event_construction_site: { id: 3 } } My concern here is how can I update the id of event_construction_site? I tried updating it like as follows: { "heading": "a", "event_construction_site": {"id": 2} } Dute to id of event_construction_site being nested field I get an error that says => The `.create()` method does not support writable nested fields by default. -
Html email title get extra spaces python django
We are trying to implement the email function using python django and it shows extra spaces in the header in the mail box like the following screenshots Does anyone have ideas about this issue? It shows in Gmail and also Outlook. I already checked css and I think it doesn't cause this problem. -
How do I send a verification email using Django rest framework?
I have found this link which is very close to what I am trying to achieve but with no luck for me so far. I have email variables and other configuration set up in my settings and these are my urls.py ... path('api/v1/auth/', include('rest_auth.urls')), path('api/v1/auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), ... when I am registering a new user, no problem, a token is returned and this is being printed in my console; Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [example.com] Please Confirm Your E-mail Address From: company@mail.cz To: mymail@gmail.com Date: Sat, 19 Dec 2020 18:24:23 -0000 Message-ID: <16084026335.1416.882339152> Hello from example.com! You're receiving this e-mail because user sstsringgg has given yours as an e-mail address to connect their account. To confirm this is correct, go to http://127.0.0.1:8000/api/rest-auth/account-confirm-email/MjU:1kqgtz:pZVAGbN8c4II4sI3mv8VvzVtnvo/ Thank you from example.com! example.com How do I switch from 'console printing' to real email sending? Any help would be much appreciated! -
How to insert multiple passanger informations like name, age, gender and berth information from html form in database using django
I am making a booking system in which I made a form which will ask form the number of passengers and on taking input it will make fields for the passengers. Now I want to insert the data into the database I do not how to do this, please help. -
How do i create object approval from aws management console or aws cli for S3 object
I am using Django boto3 module to upload images and videos to AWS S3 and also using cloudfront CDN. User create their account and upload images and videos to AWS S3 , but i want to put a check and implement admin approval for video and images . Currently, the images and videos uploaded in AWS s3 via Django app is public by default. Can it be possible via AWS management console or AWS cli to implement admin approval for images and videos? Please help. -
How can i make people selected 2 choices between 3 options?
I want users to choice 2 selection of my checkbox how can i do that by using Django? I ve tried that forms.py class KaydolForm(forms.ModelForm): secim = (('Bk','banka kartı'),('kk','Kredi Kartı'),('cek', 'çek')) secims=forms.ChoiceField(choices=secim, widget=forms.RadioSelect) but i can choose only one of them -
how to register and get data as json format from third party website in django using user authentication?
Suppose the website owner has given me a authorization token.Now using this token how to fill up a form and then get data as json format using this token from this website? -
File upload with apollo-upload-client not working with django graphene-file-upload backend
I am trying to create a simple imageboard with django backend and react frontend that are connected using GraphQL. I am having trouble trying to create a form that allows users to create new threads.The textual data uploads fine but any files attached with the form are not uploaded to the backed instead {} (an empty dictionary?) is uploaded instead of any files. I have read this answer on SO that evidently solved that users propblem, but I did not understand how and why it worked. Here is my thread model class Thread(models.Model): board = models.ForeignKey( Board, on_delete=models.CASCADE, related_name='thread' ) name = models.CharField(max_length=10, default="Anon") subject = models.CharField(max_length=100, blank=True) content = models.CharField(max_length=3000) files = models.FileField(upload_to="upload/", blank=True) , the schema for thread mutation class ThreadInput(graphene.InputObjectType): name = graphene.String() board_id = graphene.Int(required=True) subject = graphene.String() content = graphene.String(required=True) files = Upload(required=True) # grahene_file_upload.scalars.Upload class CreateThread(graphene.Mutation): thread = graphene.Field(ThreadType) class Arguments: thread_data = ThreadInput() def mutate(self, info, thread_data): thread_data['board'] = Board.objects.get(id=thread_data['board_id']) thread_data.pop('board_id') thread = Thread(**thread_data) thread.save() return CreateThread(thread=thread) and the frontend form for creating new thread. const CREATE_THREAD = gql` mutation createThread( $name: String $boardId: Int! $subject: String $content: String! $files: Upload! ) { createThread ( threadData: { name: $name boardId: $boardId subject: $subject … -
Django: How to create one Class Based view with two models which have one-to-many relationship?
I want users be able to create a post with multiple images (that's why I have separate models). How am I able to do that using class based views and one template? models.py class UserPost(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(Account,on_delete=models.CASCADE) title=models.CharField(max_length=255) text=models.TextField(null=True) category=models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) is_used=models.BooleanField(default=False) price=models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title + ' | ' + str(self.user) def get_absolute_url(self): return reverse('index') class Image(models.Model): id = models.AutoField(primary_key=True) user_post=models.ForeignKey(UserPost,default=None, on_delete=models.CASCADE) image=models.ImageField(null=True,blank=True,upload_to='images/') def __str__(self): return self.user_post.title def get_absolute_url(self): return reverse('index') -
why rating star width does not change?
I am trying to create a star rating button that will change based on the given rates. here is css code: .star-ratings-css { unicode-bidi: bidi-override; color: #c5c5c5; font-size: 14px; height: 14px; margin: 0 auto; position: relative; padding:0; margin-bottom: 3px; text-shadow: 0.8px 0.8px 0 #a2a2a2; width: 50%; } .star-ratings-css-top { color: #ffe111; padding: 0; position: absolute; z-index: 1; display: block; top: 0; left: 0; overflow: hidden; margin-left: 4px; width: 50%; } .star-ratings-css-bottom{ padding: 0; display: block; z-index: 0; border-radius: 8px; } and this is the part of html code: <div class="row" style="text-align: left;"> <div class="star-ratings-css-problem" style="width: 80px;"> <div class="row pl-5"> <div class="star-ratings-css-bottom"><span>★</span></div> <div class="star-ratings-css-top" style="width: {% widthratio post.likes post.total_like 100 %}%;"><span>★ </span></div> <div style="color: #ffe111">&nbsp;{{ idea.like_ratio }}<span class="text-muted" style="font-size: 13px;"> ({{ post.likes|add:post.loves}})</span></div> </div> </div> </div> problem is the yellow length does not change, I mean style="width: {% widthratio post.likes post.total_like 100 %}%;" is totally behaving useless in the code! but I expect change in the size of yellow part something like: -
How can I integrate my backend app in django with a frontend ui?
I have developed my backend for my web app. I am using django and django-rest-framework combined with postgresql. I am using docker and I have a docker-compose.yml file with two services, one for django and another one for postgresql. How can I create the frontend of my app? Also my project structure looks like: . ├── backend │ ├── accounts │ │ ├── admin.py │ │ ├── api.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── apartments │ │ ├── admin.py │ │ ├── api.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── backend │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── Dockerfile │ ├── expenses │ │ ├── admin.py │ │ ├── api.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations … -
Pagination after filtering in django
I have an issue when trying to use pagination after filtering. I make a search form in forms. In the first page, after searching the app show all contracts with conditions, however when I click page 2, it refreshes and shows other results. If I rewrite in search form, it will show the others result in page 2 in my form.py class ContractSearchForm(forms.ModelForm): use_required_attribute = False export_to_CSV = forms.BooleanField(required=False) class Meta: model = Contracts fields = ["contract","name"] in my view.py def list_contract(request): header= "LIST OF CONTRACT" form = ContractSearchForm(request.POST or None) queryset1 =Contracts.objects.all() #pagination paginate_by = 10 paginate_by = request.GET.get('paginate_by', paginate_by) or 10 user_list = queryset1 paginator = Paginator(user_list, paginate_by) page = request.GET.get('page',1) try: queryset1 = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) context = { "form":form, "header": header, "queryset": queryset1, 'paginate_by':paginate_by, } if request.method == 'POST': #Tạo queryset sang filter queryset2 = Contracts.objects.filter(contract__icontains=form['contract'].value(), name__icontains=form['name'].value().upper() ) #pagination when search paginate_by = 10 paginate_by = request.GET.get('paginate_by', paginate_by) or 10 user_list = queryset2 paginator = Paginator(user_list, paginate_by) page = request.GET.get('page',1) try: queryset = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) context = { "form":form, "header": header, "queryset": queryset, 'paginate_by':paginate_by, } return render (request, "customer1.html",context) … -
How to set max and min value in django form?
Suppose I want to set max value 8 and min value 5.How to set this in django form -
How can i load a VueJS app from a template using webpack?
I'm just getting started to VueJS and i'm currently trying to add it to my Django project using Webpack-Loader. I have the following two files: App.vue <template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <HelloWorld msg="Welcome to Your first Vue.js App"/> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'app', components: { HelloWorld } } </script> App02.vue <template> <div id="app02"> <img alt="Vue logo" src="./assets/logo.png"> <HelloWorld msg="Welcome to Your second Vue.js App0"/> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'app02', components: { HelloWorld } } </script> <style> #app02 { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style> Here is my main.js: import Vue from "vue/dist/vue.js"; import Vuex from "vuex"; import storePlugin from "./vuex/vuex_store_as_plugin"; import App from './App.vue' Vue.use(Vuex); Vue.use(storePlugin); Vue.config.productionTip = false; /* NOTE: unlike index.js, we are not passing props from our template, so the following render/mount syntax is ok */ new Vue({ render: h => h(App), }).$mount('#app'); And finally, here is my Django html template: {% load render_bundle from webpack_loader %} {% block content %} <h3>My second Vue app goes here</h3> <div id="app"> <app></app> </div> {% render_bundle 'chunk-vendors' %} {% render_bundle 'vue_app_02' %} {% … -
how to forward a request from flask to another api app
I want to create a dynamic handler, which can process all requests and forward them to other apps based on the database diagram -
Extend Django Queryset to add partition information to select specific partition while querying
I am working with table partitioning in MYSQL. I have partitioned my data according to Month such that there are 12 partition for each month. I have applied partition in database level but now want to introduce a queryset method in Django which lets me to select specific partition to query. from django.db import models def Person(models.Model): # My partitioned Model name = models.CharField(max_length=100) created_month = models.IntegerField() # I want query like this Person.objects.using_partition("p0", "p1").filter(name="Kamal") # Generated SQL(MYSQL): SELECT * FROM person_person PARTITION(p0,p1) where name='kamal' As seen above I want to add PARTITION(p0,p1) but after FROM table_name. -
How to set up Gunicorn and NGNIX for a Django project in a production environment?
I'm trying to re-create a production environment on my local computer before deploying the Django project I have built on a server. I am using Gunicorn and NGNIX. When I launch Gunicorn by writing gunicorn mydjangoproject.wsgi, I get my Django project displayed on the address http://127.0.0.1:8000, but without any static files. That tells me that the error lies somewhere within NGINX, but I can't figure out where. I have followed this guide in order to set up Gunicorn and NGNIX on my local computer. I have skipped steps 5 to 7 in the guide because I do not want to deal with sockets on my local computer. Here are the relevant parts of my settings.py file of my Django project: DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'production_static/') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", ] Here's the file that's located at /etc/nginx/sites-available/mydjangoproject: server { listen 8000; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /production_static/ { root /home/john/Documents/Django_projects/mydjangoproject/Version_2/mydjangoproject; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } I have done all the other steps at step 8 of the guide I linked - I … -
How filter a model by model
I'm having some trouble in filtering objects from a set of models. I have 3 classes: class Product(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) title_fa = models.CharField(max_length=80) title_en = models.CharField(max_length=80) ... class Favorite(models.Model): user = models.ForeignKey(Profile, default=None, on_delete=models.CASCADE) product = models.ForeignKey('seller.Product', default=None, on_delete=models.CASCADE) ... class Profile(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) first_name = models.CharField(max_length=80, blank=True, null=True) last_name = models.CharField(max_length=80, blank=True, null=True) shop_name = models.CharField(max_length=80, blank=True, null=True) ... I trying to fillter some thing like this : favorite_product = Product.objects.filter(id=favorite__.id) this is my view functions : def profile(request): id = request.COOKIES['id'] order__ = Order.objects.filter(sender=id) profile__ = Profile.objects.get(id=id) favorite__ = Favorite.objects.filter(user=id) favorite_product = Product.objects.filter(id=favorite__.id) return render(request, 'shop/profile/profile.html', {'order': order__, 'profile': profile__, 'favorite_product': favorite_product}) I want to show that prodoct wich they id is in Favorite model by user = id .