Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ubuntu + Django + SQLite - attempt to write a readonly database
I'm hosting my Django project with Apache on a Ubuntu 20.04 server with the standard SQLite database. It works but the database seems to be read-only. When we write to the database we get an OperationalError: attempt to write a readonly database I have tried to change the permissions according to the guide below https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I've changed the permissions of the sqlite file to 664 and gave user www-data ownership of the file and the parent folder. Yet I'm still getting the same error. Any ideas what else could be causing this problem? -
'RelatedManager' object has no attribute '_meta'
So I have a view that distuingishs between two different forms by checking the submit buttons name. The first case UserProfileForm works just great but the BankForm case returns the error 'RelatedManager' object has no attribute '_meta' Why's that? # views.py def render_dashboard_profile(request): # Get the user object user = request.user # Get the bank object bank_obj = Bank.objects.get(account_holder=user) # Create a pre-populated form instance for both models user_profile_form = UserProfileForm(instance=user.userprofile) bank_form = BankForm(instance=user.userprofile) # Create Context context = { 'user_profile_form': user_profile_form, 'bank_form': bank_form, 'bank_obj': bank_obj } if request.method == 'POST': form = {} # Determine which form was submitted if 'profile-submit' in request.POST: form = UserProfileForm(request.POST, instance=user.userprofile) # that one works elif 'bank-submit' in request.POST: form = BankForm(request.POST, instance=user.account_holder) # breaks here if form.is_valid(): form.save() return render(request, 'dashboard/dashboard_profile.html', context) else: return render(request, 'dashboard/dashboard_profile.html', context) # forms.py class BankForm(ModelForm): """ A form to change the bank data of a user """ class Meta: model = Bank fields = ['name', 'bic', 'iban'] # models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) surname = models.CharField(max_length=30) .. class Bank(models.Model): """ Stores data about the bank account of a user/investor """ account_holder = models.ForeignKey(User, on_delete=models.CASCADE, related_name='account_holder') name = models.CharField(max_length=30) bic = models.CharField(max_length=10) iban = models.CharField(max_length=30) -
Host Django on VPS Server main IP address not in Host Port
I am trying to deploy a application using Django on VPS server. It is working perfectly. All things are okay. But Here suppose this is my VPS server http://23.234.207.249 but if I click this link it is showing me a apache default page. but if I hit this http://23.234.207.249:8000 after adding port :8000 it is working and showing my application. But I want to show the same in my main IP Address. Which procedure to follow? Here I am deploying with Docker, this is my docker compose file version: '3' services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_containe command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: mysql:5.7 environment: MYSQL_DATABASE: 'gascommerce' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/dbb:/var/lib/mysql -
hey plz help me in my project i am stuck ---->>>> please
hello I am a beginner in django what i want to do is take input through voice in python and simultaneously output it on webpage using django now 1] problem is when i take input using get mehtod it start taking input through voice but without rendering the web page Eg- when start the server it start taking input without loading the page,when all the input are taken then it loads the page and shows us the value 2] when i take input using post mehtod it take input properly as i want but it does not show the output on web page simultaneously, i have seen javasricpt speech to text code snippet were we give input though voice and it shows us on webpage simultaenously but i dont want to use javascript is there any other way please help me my post method code def sample(request): bet = {} if request.method =='POST': TextToSpeech("say your username",230) username=speechtotext(5,'username') TextToSpeech("say your username",230) password=speechtotext(5,'email') print(password) bet.update({'username':username}) bet.update({'eamil':email}) return render(request,'sample.html',context=bet) below is my html code {% extends 'layout.html' %} {% load static %} {% block title %} Welcome !-COMPOSE-! {% endblock %} {% block lay %} <body onclick = "WhichButton(event)"> <div align="center" class="p-5 m-3"> … -
How to test "POST" method via url with dynamic argument (Django Rest Framework)?
I need to test some API endpoints in my app I.e. I want to create "Bookmark" using Django Rest Framework using "toggle_bookmark/<exercise_id>" url How can I substitute a value for <exercise_id> in my test_boomark.py file? This is my urls.py file: from django.urls import path, include from rest_framework import routers from api import bookmark, daily_exercise, like, upload from api.exercise import ExerciseViewSet, exercise_user_info, toggle_done from api.plan import PlanViewSet from api.practice_session import PracticeSessionViewSet from api.practice_session_exercise import PracticeSessionExerciseViewSet app_name = "api" router = routers.DefaultRouter() router.register(r"exercise", ExerciseViewSet) router.register(r"plan", PlanViewSet) router.register(r"practice-session", PracticeSessionViewSet) router.register(r"practice-session-exercise", PracticeSessionExerciseViewSet) urlpatterns = [ path("", include(router.urls)), path("upload-file", upload.upload_file, name="upload_file"), path("exercise_user_info/<user_plan_uid>/<practice_session_exercise_uid>", exercise_user_info, name="get_exercise_user_info"), path("toggle_bookmark/<exercise_id>", bookmark.toggle_bookmark, name="toggle_bookmark"), path("toggle_daily_exercise/<exercise_id>", daily_exercise.toggle_daily_exercise, name="toggle_daily_exercise"), path("toggle_like/<exercise_id>", like.toggle_like, name="toggle_like"), path("toggle_done/<user_plan_uid>/<practice_session_exercise_uid>", toggle_done, name="toggle_done"), ] Here is my test_bookmark.py file: import json from django.urls import reverse from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, APIClient from rest_framework import status from core.models import User, Bookmark class BookmarkTests(APITestCase): def test_bookmark_api(self): """ Bookmark API Test """ user = User.objects.create_user(email='test@gmail.com', name='lauren') client = APIClient() client.force_authenticate(user=user) client.post('toggle_bookmark/<exercise_id>',{"exercise_id":"123123","exercise":"exerciese1"},format="json") assert response.status_code == 201 -
Apache - HTTPS with one certificate for two different ports - Only one is accessible at a time
I'm trying to host 2 (different) servers on a single domain. One is hosted on port 8000 and the other on 8080. I want both to be accessible with HTTPS using the same certificate. Below is my conf file (both servers use the exact same configuration, just different ports and names). They both work perfectly in HTTP. However only one of the two is accessible in HTTPS for some reason, the other will load infinitely until timeout. <VirtualHost *:8080> OR <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName example.stratoserver.net ServerAlias www.example.stratoserver.net DocumentRoot /var/www/st-backend ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/st-backend/static <Directory /var/www/st-backend/static> Require all granted </Directory> Alias /static /var/www/st-backend/media <Directory /var/www/st-backend/media> Require all granted </Directory> <Directory /var/www/st-backend/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess st-backend python-home=/var/www/st-backend/stenv python-path=/var/www/st-backend WSGIProcessGroup st-backend WSGIScriptAlias / /var/www/st-backend/project/wsgi.py #HTTPS SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/example.stratoserver.net/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.stratoserver.net/privkey.pem </VirtualHost> ports.conf Listen 8080 Listen 8000 <IfModule ssl_module> Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> Can anyone point me in the right direction as to why I can't get both working with HTTPS at the same time? I would highly appreciate it. -
DRF NoReverseMatch
I am able to create and save a vote with postman, but when running a unittest with the functionality using reverse, it can't find the URL. I've tried a combination of running this with and without args/kwargs and nothing seems to work. It also appears to be in line with the documentation views.py class EntryViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def vote(self, request, *arg, **kwargs): ... tests.py def test_vote_entry_success(self): self.authenticate_client(self.other_user_data) response = self.client.post(reverse('api:entries-vote'), kwargs={'slug': self.entry.slug}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) error message django.urls.exceptions.NoReverseMatch: Reverse for 'entries-vote' with no arguments not found. 2 pattern(s) tried: ['api/entries/(?P<slug>[^/.]+)/vote\\.(?P<format>[a- z0-9]+)/?$', 'api/entries/(?P<slug>[^/.]+)/vote/$'] I used django-entensions to see map my URLs and the action is showing up as a valid route /api/entries/<slug>/vote/ api.views.EntryViewSet api:entries-vote And the test works when I hard-code the URL response = self.client.post('/api/entries/'+self.entry.slug+'/vote/') -
How to serialize multiple model object?
I am creating an API using Django Restframework which needs data from multiple models. I got many answers for my requirement but it isn't working. I have my models as follows class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title class Task_extended(models.Model): task_id = models.ForeignKey(Task, on_delete = models.CASCADE,related_name='task_extendeds') field_3 = models.CharField(max_length=200) field_5 = models.CharField(max_length=200) field_4 = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.field_3 Here's my view function @api_view(['GET','POST']) def taskList(request): tasks = Task.objects.all() serializer = TaskSerializer(tasks, many =True) return Response(serializer.data) Serializer.py class TaskSerializer(serializers.ModelSerializer): task_extendeds = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Task fields = "__all__" depth = 1 I am getting the json as following [ { "id": 2, "task_extendeds": [ 1, 2, 3 ], "title": "Start Rest Framework", "completed": false } ] What changes should I do to Serializers.py so that my json output is as following [ { "id": 2, "title": "Start Rest Framework", "completed": false, "task_extendeds": [ { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" }, { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" }, { "field_3": "Field 3 Data", "field_4": "Field 4 Data", "field_5": "Field 5 Data" } ], } ] … -
Django Not Found: /assets/js/main.js How Can I Solve this?
This is the error I am facing Not Found: /assets/vendor/venobox/venobox.css Not Found: /assets/vendor/boxicons/css/boxicons.min.css Not Found: /assets/vendor/owl.carousel/assets/owl.carousel.min.css [12/Mar/2022 13:49:17] Not Found: /assets/vendor/icofont/icofont.min.css "GET /assets/vendor/venobox/venobox.css HTTP/1.1" 404 3280Not Found: /assets/vendor/bootstrap/css/bootstrap.min.css [12/Mar/2022 13:49:17] Not Found: /assets/vendor/remixicon/remixicon.css "GET /assets/vendor/boxicons/css/boxicons.min.css HTTP/1.1" 404 3310 [12/Mar/2022 13:49:17] "GET /assets/vendor/owl.carousel/assets/owl.carousel.min.css HTTP/1.1" 404 3343Not Found: /assets/vendor/aos/aos.css [12/Mar/2022 13:49:17] "GET /assets/vendor/icofont/icofont.min.css HTTP/1.1" 404 3292 [12/Mar/2022 13:49:17] Not Found: /style.css "GET /assets/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 3316 [12/Mar/2022 13:49:17] "GET /assets/vendor/remixicon/remixicon.css HTTP/1.1" 404 3292 [12/Mar/2022 13:49:17] "GET /assets/vendor/aos/aos.css HTTP/1.1" 404 3256 [12/Mar/2022 13:49:17] "GET /style.css HTTP/1.1" 404 3208 Not Found: /assets/js/main.js [12/Mar/2022 13:49:17] "GET /assets/js/main.js HTTP/1.1" 404 3232 my css was not loaded in my template and it shows this error in terminal please help me to solve this -
using django can you build form
[enter image description here][1] can you make form exact same [1]: https://i.stack.imgur.com/D2Nkp.png -
Why the categories is not shown in the dropdown?
<a href="#">Categories</a> {% for categories in links %} <ul class="dropdown"> <li><a href="#">{{ category.category_Name }}</a></li> </ul> {% endfor %} I'm not able to see drop-down list. -
Django button like Without Page Refresh Using Ajax and Load html page with ajax info
I am doing a project which has a like or un-like button for each post on web-page. But when I click on like, I get a page that looks like this (http://127.0.0.1:8000/give_like/2): {"post_to_like": 2} view.py def give_like(request, post_to_like): like = Likes(user=request.user, post = Post.objects.get(id=post_to_like)) checker = [like.post_id for like in Likes.objects.filter(user = request.user)] if post_to_like in checker: Likes.objects.filter(post_id=post_to_like, user = request.user).delete() else: like.save() return JsonResponse({'post_to_like':post_to_like}) how to load the whole page correctly as html but without reloading the whole page and get info that Im already follow this post so i should see button un-like and the rest of the page? js.js var like = document.getElementById("like"); likeDislike(like, function() { fetch(`/give_like/${like.dataset.post_to_like}`) .then(response => response.json()) .then(data => { like.querySelector('small').innerHTML = data.total_likes; }); } ); index.html <small><p id="total_likes" > {{post.current_like}} </p></small> urls.py path("give_like/<int:post_to_like>", views.give_like, name="give_like"), -
I'm trying to Create class based Rest_Api in Python django than show some error
This is my Views.py file code-: from django.shortcuts import render from.models import* from . serializers import ANI_News_DetailSerializer from rest_framework.decorators import APIView from rest_framework.response import Response from rest_framework import status class NewsList(APIView): def get(self, request): news = ANI_News_Detail.objects.all() serializer = ANI_News_DetailSerializer(news, many=True) return Response(serializer.data) def post(self,request): serializer = ANI_News_DetailSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) This is Apps url.py file-: from pathlib import Path from django.urls import path from django.conf.urls.static import static from django.conf import settings #from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = [ path('',views.home,name='home'), #path('news/',views.news_list), #path('news/<int:pk>/',views.news_details) Path('news/', views.NewsList.as_view()) ]+ static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) Project Url file-: from django.contrib import admin from django.urls import path,include #from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('admin/', admin.site.urls), path('',include('articles.urls')), #path('news/',views.ANI_newsList.as_view()), ] If i can run the commands as runserver than Show the Error-: folder\myblogsite22\myblogsite\myblogsite\urls.py", line 22, in <module> path('',include('articles.urls')), File "C:\Users\Gaurav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Gaurav\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Gaurav\Desktop\sandeep\san\New … -
Create Django environment file as a Secret Manager secret Gcloud
I'm trying to set django environment file for secret manager secret. Need to know the windows command prompt equivalent of this command: ''' echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env ''' -
How do I put ajax on django class based update view
I have two submit buttons in my web-page. One of them is for submitting the form. The other one uses ajax to send the text inside a text-box to the server, processes it and returns back the result (in my case summary of the text) into another text-box. I implemented it using ajax call of this kind: $(document).on('submit','#report-text',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "create-post" %}', data: { unsummarized_news : $("#id_news").val(), csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ fetch('{% url "create-post" %}', { headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, }) .then(response => { return response.json() }) .then(data => { console.log(data) document.getElementById("id_title").value = data['summary']; }) } }) }); This is the view I used, for creating post and ajax call: class CreatePost(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): if request.is_ajax(): data = { 'summary': summary } return JsonResponse(data) form = PostForm() context = { 'form': form, } return render(request, 'posts/create_post.html', context) def post(self, request, *args, **kwargs): if 'news_submit_form' in request.POST: form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.publisher = request.user new_post.save() form = PostForm() # Clearing the form after submission if 'unsummarized_news' in request.POST: global summary unsummarized_news = request.POST['unsummarized_news'] summary = get_summary(unsummarized_news) return redirect('home') It works fine when creating a new post. … -
Serving React and Django on Nginx with SSL and Domain/Subdomain
I have a React application and Django application served by Nginx. I would like to find a way to serve React on domain.com and Django on api.domain.com. Additionally, both frontend and backend must use HTTPS so they must be listening on port 443 at the same time. Right now, I have an SSL certificate for the frontend. Will changing the server_name for the frontend to domain.com and the backend to api.domain.com be enough to handle my requirements? Is this a better configuration than having my API be served under domain.com/api/? NGINX Server Block for Frontend server { root /home/ubuntu/example/frontend/build; server_name example.software www.example.software; index index.html index.htm; listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.software/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.software/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.software) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name example.software www.example.software; return 404; # managed by Certbot } NGINX Server Block for Backend server { listen 80 default_server; listen [::]:80 default_server; location = /favicon.icon { access_log off; log_not_found off; } location /static/ { root … -
In django what is the use of urls.py for each app?
I am making a django project and i learnt that we need to create a urls.py file for each app created within project. Can anyone please tell what is the purpose of this because we have one urls.py file for the main project, isn't that enough? -
How to save foreign key data using forms.py?
urls.py ... path('restaurant/menu/', r_view.Menu, name='menu'), ... menu.html <form method="POST" id="menuForm" autocomplete="off" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="form-inline"> <div class="form-group mb-4"> {{ form.item|as_crispy_field }} </div> <div class="form-group mb-4"> {{ form.itemImage|as_crispy_field }} </div> <div class="form-group mb-4"> {{ form.price|as_crispy_field }} </div> <div class="form-group mb-4"> {{ form.category|as_crispy_field }} </div> </div> <button type="submit" class="col-md-12 myBtn">Submit</button> </form> views.py def Menu(request, restaurantID): restaurant = get_object_or_404(Restaurant_Account, restaurantID=restaurantID) form = MenuForm() if request.method == 'POST': form = MenuForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.restaurant = restaurant instance.save() messages.success(request, "Saved successfully!") return redirect('r_index') context = {'form':form} return render(request, 'restaurant/menu.html', context) forms.py class MenuForm(forms.ModelForm): restaurantID = Restaurant_Account.objects.filter(restaurantID='restaurantID') item = forms.CharField(required=True) itemImage = forms.ImageField(required=False, label='Item image') price = forms.DecimalField(required=True) category = forms.ChoiceField(choices=CATEGORY) class Meta: model = Menu fields = ('item', 'itemImage', 'price', 'category') models.py class Menu(models.Model): menuID = models.AutoField(primary_key=True) restaurantID = models.ForeignKey(Restaurant, on_delete=models.CASCADE) item = models.CharField(max_length=100) itemImage = models.ImageField(upload_to='images/', blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField( max_length=20, choices=[('', 'Choose category'),('Appetizer', 'Appetizer'),('Entree', 'Entree'),('Drink', 'Drink'),('Dessert', 'Dessert')]) def __str__(self): return self.item I'm new to Django. I made a form for saving menu data. If the user fills the form and click the submit button every data should be saved in the Menu table. I have no idea how to save restaurantID, which … -
Why my django project's send_mail isn't working properly?
I was creating a project in which the website will automatically send the emails to the member who's last date of bill payment is today. To do so I created a method in the model class of Entry in my django project. I have fully configured the smtp settings in project/settings.py . The email is going to the member but the issue is that each time the user refreshes the page the email is sent. It is sending email again and again. I am tired out of it, please tell me the solution of this problem. here is entries/models.py from django.db import models from django.contrib.auth import get_user_model import datetime import uuid state_choices = (("Andhra Pradesh","Andhra Pradesh"),("Arunachal Pradesh ","Arunachal Pradesh "),("Assam","Assam"),("Bihar","Bihar"),("Chhattisgarh","Chhattisgarh"),("Goa","Goa"), ("Gujarat","Gujarat"),("Haryana","Haryana"),("Himachal Pradesh","Himachal Pradesh"),("Jammu and Kashmir ","Jammu and Kashmir "),("Jharkhand","Jharkhand"),("Karnataka","Karnataka"), ("Kerala","Kerala"),("Madhya Pradesh","Madhya Pradesh"),("Maharashtra","Maharashtra"), ("Manipur","Manipur"),("Meghalaya","Meghalaya"),("Mizoram","Mizoram"),("Nagaland","Nagaland"), ("Odisha","Odisha"),("Punjab","Punjab"),("Rajasthan","Rajasthan"),("Sikkim","Sikkim"),("Tamil Nadu","Tamil Nadu"),("Telangana","Telangana"),("Tripura","Tripura"),("Uttar Pradesh","Uttar Pradesh"),("Uttarakhand","Uttarakhand"),("West Bengal","West Bengal"),("Andaman and Nicobar Islands","Andaman and Nicobar Islands"),("Chandigarh","Chandigarh"),("Dadra and Nagar Haveli","Dadra and Nagar Haveli"),("Daman and Diu","Daman and Diu"), ("Lakshadweep","Lakshadweep"),("National Capital Territory of Delhi","National Capital Territory of Delhi"),("Puducherry","Puducherry")) from django.core.mail import send_mail class Entry(models.Model): entry_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="entries") member = models.CharField(max_length=200) member_id = models.CharField(max_length=25, unique=True) email_address = models.EmailField(max_length=252, null=False, blank=False) email_send = models.BooleanField(default=True) is_email_sent = models.BooleanField(default=False) state … -
Using django filer
I want to be able to reuse the same image and I found that django-filer is perfectly what I was looking for. But, I didn't find any documentation or tutorial about how to use this package (move from basic ImageField to django filer). The documentation is only explaining about how to use it on fresh new projects. This is the best link about explaining how to use django-filer https://wellfire.co/learn/migrating-to-django-filer/. But it lacks detail in the explanation and I found an error while trying it. One more question. I want to use django-filer only in admin (only admin who can reuse the same image). But I also have form for the basic users. I want to use the basic upload image field in the form so the basic user doesn't have the "reuse image" feature. Is there any solution for this? or is there any better package that is similar to django filer? -
Python Flask - How to download a file with send_from_directory AND display text output in browser
I'd like to be able to display a message to the user after a download is triggered via send_from_directory. @app.route('/downloadFile', methods=['GET']) def download(): return send_from_directory(output_directory, "myfile.txt", as_attachment=True) This will trigger a download after the /downloadFile endpoint is visited, but in addition to the download being triggered, I'd like to have output in the browser that says something like "file download triggered". Is there a way to achieve this? If I wasn't using send_from_directory, I could do something like this to return some JSON return {'Status': 'file download triggered'} I'm looking for a way to combine the two, that way the user doesn't see a blank screen when they hit this endpoint. -
Show all foreign key fields in Django admin create page
I am new with Django and mysql so i have a question: I am using admin model for my first django web app I have 2 of model like that: class Report(models.Model): week = models.CharField() customer_account = models.CharField() release_name = models.ForeignKey(ReleaseInformation, on_delete=models.CASCADE, default='') class ReleaseInformation(models.Model): release_name = models.CharField(max_length=50, blank=False, null=True) release_date = models.DateField() process_status = models.CharField(max_length=50, choices=Constant.QUALITY, default=None) With release name is ForeignKey from ReleaseInformation So in create a new model of Report, I can see and select Release name. My question is: How can I display all fields of ReleaseInformation() When I select a object of it from create Report page Ex: as in the picture, it will show all field of Tool when i select Tool enter image description here Thanks for your help, and sorry because my english is not good -
How do I display fields of other models in a create view in Django?
I'm trying to create some entries in the database. I am not able to input anything for the Address models. I would like to be able to add the individual fields of the shipping_address. How can I achieve this? serializer class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('email', 'password', 'first_name', 'last_name', 'mailing_address', 'shipping_address', 'phone', 'is_active', 'is_staff', 'is_approver') def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) models class Address(models.Model): first_address = models.CharField(max_length=255, blank=True, default='') second_address = models.CharField(max_length=255, blank=True, default='') city = models.CharField(max_length=255, blank=True, default='') state = models.CharField(max_length=255, blank=True, default='') zip = models.CharField(max_length=255, blank=True, default='') class Phone(models.Model): phone_number = PhoneField(blank=True, help_text='Contact phone number') class ShippingAddress(models.Model): first_address = models.CharField(max_length=255, blank=True, default='') second_address = models.CharField(max_length=255, blank=True, default='') city = models.CharField(max_length=255, blank=True, default='') state = models.CharField(max_length=255, blank=True, default='') zip = models.CharField(max_length=255, blank=True, default='') class User(AbstractBaseUser, PermissionsMixin): """Custom user model that suppors using email instead of username""" email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=True, default='') last_name = models.CharField(max_length=255, blank=True, default='') password = forms.CharField(widget=forms.PasswordInput) phone = models.ForeignKey(Phone, on_delete=models.CASCADE, null=True, blank=True) mailing_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) shipping_address = models.ForeignKey(ShippingAddress, on_delete=models.CASCADE, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_approver = models.BooleanField(default=False) objects … -
Django-mptt get cumulative count of item inside each category
i'm using django-mptt i'm trying to get all categories with the count of items inside each category but i get that error OperationalError at /items/ (1054, "Unknown column 'items_category.lft' in 'where clause'") from my view.py categories = Category.objects.add_related_count( Category.objects.all(), # Queryset Item, # Related mobile 'category', # Name of the foreignkey field 'count', # Name of the property added to the collection cumulative=True) # Cumulative or not. print(categories) model.py class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, null=True, blank=True, ) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by=['name'] def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" class Item(models.Model): category = TreeForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=250 ) -
Django : How can we manage groups and permissions if we use the Microsoft Azure Authentication
I am a newbee in Django and I would like to know how I can manage groups and permission for differents users if I used the Microsoft Authenticatication that is explained in the tutorial https://docs.microsoft.com/en-us/graph/tutorials/python. Can we manage that in Azure AD ? Or should we add them the users to the django authentication after the Microsoft authentication is done ? Can anyone explain me because I do not get how I should create groups after the Microsoft authentication ? Thank you