Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
AWS Elastic Beanstalk RDS MacOS mysqlclient not working
I'm trying to set up an application with Django through Elastic Beanstalk and MySQL through RDS. I can successfully use the application on localhost with the MySQL RDS database. When I deploy, I have problems. I get "111: Connection refused" but maybe more importantly "mysql_config: command not found, mariadb_config: command not found, mysql_config: command not found" Posts on here talk about using yum in a packages.config file, I tried those suggestions without success. Isn't yum for use on operating systems other than MacOS? I followed the instructions here: https://pypi.org/project/mysqlclient/ And of course mysqlclient is in my requirements.txt Obviously I need the files mentioned above, but how do I get them? -
Django - After Register, Data Should Go To 2 Different Tables (Customer & User)
I am creating an e-commerce website where people can choose to login or not but still the can order and checkout (even if you are an AnonymousUser or Guest user). Now, I am making a login and register form in my website. The login form works and looks good but the register form wasn't working and throwing an error that said "RelatedObjectDoesNotExist at / User has no customer." I think the reason is that when I register, it only makes a User in database but didn't register anything in the Customer table (which consists Name and Email). How can I register a Customer and User at the same time when I hit the "Submit" button? And how can I make that specific User have "Staff status" only and cannot make changes in the Admin site? Also, I want to add new fields in the Register form for Name and Email that will go directly to the Customer table. I tried to do this one but it doesn't work and throwed and error that says "django.core.exceptions.FieldError: Unknown field(s) (name) specified for User". Here's what I did: from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import … -
How can I deal with too many open file descriptors in Python/Django?
My Django app has multiple models that have some file fields: class MyModelA(models.Model): field1 = models.FileField(...) field2 = models.FileField(...) field3 = models.FileField(...) class MyModelB(models.Model): field1 = models.FileField(...) field2 = models.FileField(...) field3 = models.FileField(...) In order to generate some test data for my app that includes fake files, I do this: my_app/management/commands/generatetestdata.py: class Command(BaseCommand): def handle(self, *args, **options): self.generate_model_a_test_data() self.generate_model_b_test_data() ... def generate_model_a_test_data(self): field1_data = Path("/path/to/field1/sample/file").read_bytes() field2_data = Path("/path/to/field2/sample/file").read_bytes() for _ in range(1000): instances = [] instances.append(MyModelA( field1=ContentFile(field1_data, name="Some File Name"), field2=ContentFile(field2_data, name="Some File Name"), )) MyModelA.objects.bulk_create(instances) That's not the exact code I use, but that's the idea. There are only a few actual files that I'm reading off the filesystem. I read them into memory, and create a ton of ContentFile instances, which, when saved, actually copies those files to my media directory. Yes, not as efficient as using something like symlinks, but that's fine. The problem I'm seeing is that sometimes, running python manage.py generatetestdata succeeds, while other times, it fails after several minutes with: django.db.utils.OperationalError: unable to open database file When it does fail, it's after creating thousands of files (NOT immediately after running the command), so it's definitely not a permissions issue. I suspect that the reason … -
Django debug toolbar
Can't see the Django Debug Toolbar on a simple html doc. New to Django and the tutorial i'm doing is a little outdated. I have done all the requirements such as ensure STATIC_URL = "static/", INSTALLED_APPS = ["django.contrib.staticfiles"], Backend and APP_DIRS is correct. debug_toolbar is in INSTALLED_APPS, added the added the debug url to urlpatterns list, Middleware is done and 'debug_toolbar.middleware.DebugToolbarMiddleware' is at the top. Internal IPS is set to 127.0.0.1, if i change it the ourcecode of the webpage removes the code for debug toolbar. Made sure that Debug = True I use pycharm mostly, heard that might be an a problem using the runserver command so tried it on cmd as well. multiple times. when viewing the page source i see the code for the debug toolbar as well as my html. thought maybe my html is written poorly(never used it before) this is what it looks like word for word. <html> <head> <title>Example</title> </head> <body> <p>This is an example of a simple HTML page with one paragraph.</p> </body> </html> Latest version of django-debug-toolbar installed and django. Tried different chrome, edge and explorer browsers, all are the same. I've tried a few tricks like def show_toolbar(request): return True … -
django ajax get model data in JS variable
Trying to get my model data from django views.py in home.html javascript variable using AJAX. So far I'm at : Views.py: def flights_list(request): flights = serializers.serialize("json", Flights.objects.all()) return JsonResponse({"flights": flights}) Ajax: function get_data() { $.ajax({ url: '', //Not sure what to put here. datatype: 'json', type: 'GET', success: function (data) { alert("Got data!") locations = {{ flights }}; } }); }; $(document).ready(function(){ setInterval(get_data,5000); }); Every 5 seconds i'm getting alert "Got data!" But when I'm trying to pass variable location = {{ flights }}; Then locations is empty. in ajax url:'' i suppose to have my views.py location? as when trying to alert("Got data!" + data) then my whole html is in that data variable.. Am i doing something wrong here?