Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to grenerate graph of part of a database using django_extensions
I'm following this tutorial https://medium.com/@yathomasi1/1-using-django-extensions-to-visualize-the-database-diagram-in-django-application-c5fa7e710e16 To generate graphic ER diagrams on django and because the database is to big, the graph is a little confusing so I want to create more than one file with the different relations. My question is, how to create something like this? python manage.py graph_models app1 -a -I model1, model2 -o output.png > output.dot Being app1 one of the aplications and model1, model2 two models located in another app. Is that even possible? Or do I have to enter manually all the models involved. If someone can help me with this I will appreciate it Cheers -
Django and HTMX for dynamically updating dropdown list in form.field
Using django and htmx I need to do the following. In a parent form create-update.html I need to give a user the ability to add another 'contact' instance to a field that contains a drop list of all current 'contact' instances in the database. I want the user to click an add button next to the sro.form field, which renders a modal containing a child form new_contact.html. The user will then enter the new 'contact' instance into the child form in the modal form new_contact.html and click save. This will cause the new contact instance to be saved to the database via create_contact_view(), and for the the sro form field in the parent form create-update.html to be replaced via an AJAX call, with an refreshed dropdown list I've partially completed this. I have a working modal form which is saving new 'contact' instances to the database, but the sro.form field just disappears and isn't reloaded. Here's my code. Many thanks. views.py class ProjectCreateView(CreateView): model = Project form_class = ProjectUpdateForm template_name = "create-update.html" def get_context_data(self, **kwargs): context = super(ProjectCreateView, self).get_context_data(**kwargs) context["type"] = "Project" context["new_contact_url"] = reverse("register:new-contact") # to create new url return context def form_valid(self, form, *args, **kwargs): mode = form.cleaned_data["mode"] … -
DJango Microsoft auth allauth automatic
I have a program in DJango. I have a second program called "users". Inside I have implemented login and login with microsoft authentication. I have done this using the "allauth" library. Now I want you when accessing the page, (without having to access the "/login" page) check if you have a microsoft account. That is, when I enter the main page: "/", it takes me to the page to choose a microsoft account in the event that it has one. Without having to press any buttons. That's possible? That it automatically connects if I am connected to a Microsoft account. This is my view: def home(request): if request.user.is_authenticated: return redirect('main_page') else: return render(request, 'home.html') I don't know if I explained myself correctly, I want the Microsoft authentication to be automatic -
My .pkpass file not working for iOS system, but in app Passes(android) I can see the content
I use Django-wallet for generation of .pkpass files. Everything works in Android, but for iOS I can't see the card Firstly I used certificates from another computer, but then I regenerated all certificates and etc on my own. Also I resized images Anything above doesn't helped -
Does xhtml2pdf also execute <script> tag in html?
I am trying to create a pdf from html in Django and I am using xhtml2pdf python module. But the issue is, it is not executing script tag in html. So does xhtml2pdf even execute script tag in html?? if not, please recommend any other module that does!! -
Video not playing in server (Django)
I am fairly new to Django and currently I'm making a Youtube Clone to understand Django in depth. So the problem I'm facing right now is that I can't seem to get the video to play in the server. I've spent a lot of time trying but can't seem to find an answer! I'll provide what I think relates to my problem; 1) Template ` video.html <video width="320" height="240" controls> <source src="{{ video.path }}" type="video/mp4"> Your browser does not support the video tag. </video>` 2) views.py `class VideoView(View): template_name = 'base/video.html' def get(self, request, id): #fetch video from DB by ID video_by_id = Video.objects.get(id=id) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) video_by_id.path = 'http://localhost:8000/get_video/'+video_by_id.path context = {'video':video_by_id} if request.user.is_authenticated: print('user signed in') comment_form = CommentForm() context['form'] = comment_form comments = Comment.objects.filter(video__id=id).order_by('-datetime')[:5] print(comments) context['comments'] = comments return render(request, self.template_name, context) class VideoFileView(View): def get(self, request, file_name): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file = FileWrapper(open(BASE_DIR+'/'+file_name, 'rb')) response = HttpResponse(file, content_type='video/mp4') response['Content-Disposition'] = 'attachment; filename={}'.format(file_name) return response` 3) models.py `class Video(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=300) path = models.CharField(max_length=100) datetime = models.DateTimeField(auto_now=True ,blank=False, null=False) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) ` 4) urls.py ` app_name = 'Youtube' urlpatterns = [ path('home/', HomeView.as_view(), name='homeview'), path('login/', LoginView.as_view(), name='loginview'), path('register/', RegisterView.as_view(), name='register'), path('new_video/', … -
How to split django app in multiple folder
I like to split my django app here in my case it's called Core in multiple folders like in the picture. Example Bank ---views ---urls ---models ---serializer Currency ---views ---urls ---models ---serializer I put in each folder the __init.py__ file here the init file from bank folder ` from .models import BimaCoreBank` and here the models.py for bank folder from core.abstract.models import AbstractModel from core.country.models import BimaCoreCountry from core.state.models import BimaCoreState class BimaCoreBank(AbstractModel): name = models.CharField(max_length=128, blank=False, unique=True) street = models.CharField(max_length=256, blank=True, null=True) street2 = models.CharField(max_length=256, blank=True, null=True) zip = models.CharField(max_length=16, blank=True, null=True) city = models.CharField(max_length=16, blank=True, null=True) state = models.ForeignKey( BimaCoreState, on_delete=models.PROTECT) country = models.ForeignKey( BimaCoreCountry, on_delete=models.PROTECT) email = models.EmailField(blank=True, null=True) active = models.BooleanField(default=True) bic = models.CharField(max_length=16, blank=True, null=True) def __str__(self) -> str: return self.name class Meta: ordering = ['name'] permissions = [] app_label = "BimaCoreBank" and here the urls.py file from bank folder from rest_framework import routers from core.bank.views import BimaCoreBankViewSet router = routers.DefaultRouter() app_name = 'BimaCoreBank' urlpatterns = [ router.register(r'bank', BimaCoreBankViewSet, basename='bank'), ] It's the same on each folder,juste I changed the name of the class, Now in the __init.py__ file in core folder( the app folder that containt all the subfolders) from . import bank from … -
The 'Access-Control-Allow-Origin' header contains multiple values ERROR
I have an app with react frontend and django backend. I have a problem, when the frontend wants to get a file from the backend, an error appears Access to XMLHttpRequest at 'http://api.(site name).com/documents/15/' (redirected from 'http://api.(site name).com/documents/15') from origin 'http://www.(site name).com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://www.sitename.com, *', but only one is allowed. my nginx.conf on my server server { server_name api.sitename.com; listen 80; server_tokens off; client_max_body_size 10m; root /var/html/; # location ~ /.well-known/acme-challenge/ { # root /var/www/certbot; # } location / { if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = OPTIONS ) { add_header "Access-Control-Allow-Origin" '*' always; add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD"; add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept"; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; return 204; } # proxy_set_header Host $host; # proxy_set_header X-Forwarded-Host $host; # proxy_set_header X-Forwarded-Server $host; # proxy_pass http://backend:8000; } location /media/ { autoindex on; } location /docs/ { root /usr/share/nginx/html; try_files $uri $uri/redoc.html; } location … -
Group by with related_name relation using Prefetch
I need to make an API with this body structure for graph with multiple lines: [ { "title": "Test title", "dots": [ { "date": "2023-03-03", "sum_weight": 5000 }, { "date": "2023-03-06", "sum_weight": 1500 } ] } ] But I have a problem with Prefetch, since it's not possible to use .values() to do group_by date during query. Right now my ungrouped API looks like this: [ { "title": "Test title", "dots": [ { "date": "2023-03-03", "sum_weight": 5000 }, { "date": "2023-03-06", "sum_weight": 500 }, { "date": "2023-03-06", "sum_weight": 1000 } ] } ] My code right now: Query: groups = Group.objects.prefetch_related( Prefetch("facts", queryset=Facts.objects.order_by("date").annotate(sum_weight=Sum("weight"))) ) Serializers: class GraphDot(serializers.ModelSerializer): sum_weight = serializers.SerializerMethodField() def get_sum_weight(self, obj): if not hasattr(obj, 'sum_weight'): return 0 return obj.sum_weight class Meta: model = Facts fields = read_only_fields = ("date", "sum_weight",) class FoodGraphSerializer(serializers.ModelSerializer): dots = GraphDot(many=True, source="facts") class Meta: model = Group fields = read_only_fields = ("title", "dots") Is there any way to make a query that is grouped by date so my sum_weight annotation is summed within it? -
unable to authenticate the django login page in mysql
[I am unable to authenticate django login session with mysql] already tried below things (https://i.stack.imgur.com/rPFWE.png) -
django autocomplete-light with model's foreignkey shows select box not a textbox
I want to upload files in my server using POST method but when I make a form there are something problem. My problem is I want to make autocomplete but web shows only select box. Even there is no select options.(when I used it without autocomplete-light library I can choose options in uuids) even I followed autocomplete-light library official docs. The codes are my django code views, template, forms, models, urls #views.py class Auto_uuid(autocomplete.Select2QuerySetView): auto_class = Uuid def get_queryset(self): if not self.request.user.is_authenticated: return self.auto_class.objects.none() qs = self.auto_class.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class Class_stat(generic.View): form_class = StatForm def get(self, request): form = self.form_class() return render(request, "myapp/stat_input.html", {'form':form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("myapp:home") return render(request, "myapp/stat_input.html", {'form':form}) #template stat_input.html {%extends 'base.html' %} {% block content %} <h2>Upload raw data</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> {{form.uuid}} </div> <div> {{form.as_p}} </div> <button type="submit" class="btn btn-primary">upload</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endblock %} #forms.py class StatForm(forms.ModelForm): class Meta: model = Stat_file fields = '__all__' widgets = { 'uuid': autocomplete.ModelSelect2(url="myapp:auto") } #models.py class Stat_file(models.Model): uuid = models.ForeignKey(Uuid, on_delete=models.CASCADE, default=None) myfile = models.FileField(upload_to=user_stat_directory_path,max_length=400) cellline = models.CharField(max_length=100, default=None) cohort = models.ForeignKey(Cohort, on_delete=models.CASCADE) perttype = models.ForeignKey(PertType, on_delete=models.CASCADE) class … -
How to create two databases in django app with docker-compose
I connect can to my pgadmin with db1 but impossible to connect in with db2. I got this error Unable to conect to server: ... (see picture). I have seen some post but none of them resolve my problem. version: "3.9" services: web: build: context: . dockerfile: ./Dockerfile entrypoint: /code/docker-entrypoint.sh restart: unless-stopped ports: - "8000:8000" depends_on: - db1 - db2 volumes: - .:/code db1: container_name: database1 image: postgres:14.4 restart: unless-stopped ports: - "5432:5432" environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres db2: container_name: database2 image: postgres:14.4 restart: unless-stopped ports: - "5433:5433" environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres pgadmin: container_name: pgadmin image: dpage/pgadmin4:6.20 restart: unless-stopped environment: PGADMIN_DEFAULT_EMAIL: admin@admin.com PGADMIN_DEFAULT_PASSWORD: admin PGADMIN_CONFIG_SERVER_MODE: 'False' volumes: - ./pgadmin:/var/lib/pgadmin ports: - '8001:80' depends_on: - db1 - db2 - web -
Not able to run selenium in headless mode on linux server
Error: Message: unknown error: Chrome failed to start: exited abnormally. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Description: I'm following this post and official document to install and setup Selenium in headless mode on my server. When I run it locally on my server, it works, but when I access it after setting up Nginx and a Service file for my Django site, it gives me the above error. After looking at several answers, I checked these points, and they exist in my project or in my system. google chrome browser (version - 111) selenium installed chrome driver (version - 111) added chrome driver in $PATH above points I've added if I'm missing somthing or any other information required please let me know. -
Error: PROJ: proj_create: unrecognized format / unknown name
I have installed Terria JS and Cartoview. when i upload layers in Cartoview then they are uploaded but the following errors come: Error Message: PROJ: proj_create_from_database: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code, datum_auth_name, datum_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM geodetic_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name Error Message: PROJ: proj_create: unrecognized format / unknown name Error Message: Cannot find coordinate operations from ' to '> I installed gdal error handler and then was successful to get these error messages. can anyone kindly tell why they are coming? I have also heard that these errors are due to PROJ library. Please have a look. Thanks! -
Django admin inlines from second model when first model child has OneToOne relationship with other second model
Admin.py has GroupAdmin and GroupItemsInline but also want an extra inline with OrderItems groupped by item and total item_qty calculation as above. It could be possible add extra inline with aggregates from OrderItems In GroupAdmin? models.py from django.db import models #Order class Order(models.Model): order_num = models.CharField(null=True, max_length=10, unique=True) def __str__(self): return self.order_num #contains the detail of an order class OrderItems(models.Model): parent_order = models.ForeignKey(Order, on_delete=models.CASCADE) item = models.CharField(null=True, max_length=32) item_qty=models.IntegerField(null=True) def __str__(self): return self.item +' '+ str(self.item_qty) #Allow grouping orders into a group class Group(models.Model): group_num = models.CharField(null=False, unique=True, max_length=10) def __str__(self): return self.group_num #Contains the orders grouped in a group #related with Group via ForeignKey #related with Order via OneToOneField class GroupItems(models.Model): parent_group = models.ForeignKey(Group, on_delete=models.CASCADE) grouped_order = models.OneToOneField(Order,on_delete=models.CASCADE) def __str__(self): return self.grouped_order` **admin.py** `from django.contrib import admin from .models import Order, OrderItems, Group, GroupItems class OrderItemsInline(admin.TabularInline): model = OrderItems class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemsInline] class GroupItemsInline(admin.TabularInline): model = GroupItems class GroupAdmin(admin.ModelAdmin): inlines = [GroupItemsInline] admin.site.register(Order, OrderAdmin) admin.site.register(Group, GroupAdmin) admin.py from django.contrib import admin from .models import Order, OrderItems, Group, GroupItems class OrderItemsInline(admin.TabularInline): model = OrderItems class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemsInline] class GroupItemsInline(admin.TabularInline): model = GroupItems class GroupAdmin(admin.ModelAdmin): inlines = [GroupItemsInline] admin.site.register(Order, OrderAdmin) admin.site.register(Group, GroupAdmin) Can access OrderItems data related … -
How to filter query objects by date range in DRF?
I have simple model: models.py class Report(models.Model): title = models.CharField(max_length=250) created_date = models.DateField() Created filters.py file and using django-filters package wrote FilterSet: from .models import Report class ReportFilter(django_filters.FilterSet): created_date = django_filters.DateFromToRangeFilter() class Meta: model = Report fields = ['created_date'] Simple views.py: from .filters import ReportFilter from .models import Report def Reports(request): reports = Report.objects.all() myFilter = ReportFilter(request.GET, queryset=reports) reports = myFilter.qs return render(request, 'dashboard/index.html', {'reports': reports, 'myFilter': myFilter}) And the last file index.html: {% block content %} <form method="get" style="display: block; width: 335px; margin: 20px auto;"> {{myFilter.form}} <button type="submit">Search</button> </form> {% if reports %} {% for report in reports %} <tr> <td> {{ report.title }} </td> <td> {{ report.created_date }} </td> </tr> {% endfor %} {% endif %} </table> {% endblock content %} Question in short: How to do it DRF? (beginner in DRF) What I tried so far: serializers.py from rest_framework import serializers from .models import Report class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = '__all__' views.py from .filters import ReportFilter from .serializers import ReportSerializer from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend from .models import Report class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer filter_backends = [DjangoFilterBackend,] filterset_class = ReportFilter Did not change filters.py and added all … -
filter by parent field in django queryset
Hi i want to get all the items of a coffee shop by its slug . as it is clear it saves the pk not the slug in the model. Is there any way to get this instead of finding cafe pk and etc. i am searching for some thing like just one query for it. here is what i coded : url path( "<str:cafe_slug>/", ProfileList.as_view(), name="get_item_menu", ), in view def get(self, request,cafe_slug): queryset = Item.objects.filter(cafe__slug=cafe_slug) model class Item(models.Model): name = models.CharField(max_length=256, unique=True,) cafe = models.ForeignKey(CoffeeShop, on_delete=models.CASCADE) class CoffeeShop(models.Model): name = models.CharField(max_length=256, unique=True) slug = models.CharField(max_length=256, unique=True,) -
Complex filtering with Q() Django
I have models Order and User: class Order(Model): ... status = CharField(choices=STATUS, default=NEW, max_length=20) referral_user = ForeignKey("app.User", CASCADE, 'referal', blank=True, null=True) operator = ForeignKey("app.User", CASCADE,'operator', blank=True, null=True) class User(Model): ... orders_for_all_operators = BooleanField(default=True) operators = ManyToManyField("User", related_name="admins") I need to filter orders for operators like this: Status: New Operator: requested user or no operator. Order's referral_user: has the requested user in their operators field or orders_for_all_operators = True I've tried this code but it's not working: qs = queryset.filter(Q(Q(referral_user__in=self.request.user.admins.all()) | Q(user__orders_for_all_operators=True)) | Q(Q(operator=None) | Q(operator=self.request.user))) -
Error message when I run my Django server with sudo. "ImportError: Couldn't import Django..."
I have a Django server in our local environment that we run some scripts through. I wanted to get rid of having to run it with the portnumber attached to the IP when i run the web-app. So instead of running it with port 8000 i want to run it with 80. requirement.txt: asgiref==3.6.0 backports.zoneinfo==0.2.1 certifi==2022.12.7 charset-normalizer==3.0.1 Django==4.1.7 idna==3.4 oauthlib==3.2.2 requests==2.28.2 requests-oauthlib==1.3.1 sqlparse==0.4.3 urllib3==1.26.14 I found some sources (*) that said that i could run it with sudo to get rid of the initial: 'Error: You don't have permission to access that port.' message. (*)Django: Error: You don't have permission to access that port But when i run the command sudo python manage.py runserver 0.0.0.0:80 i get the error message: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> if __name__ == '__main__': main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The … -
django-celery with redis broker, new preiodic task not starting
I have a drf project and I use celery with redis broker. every thing working fine and run smoothly, but when I try to add a new preiodic task , I see it created, I see it in the celery beat but the task never run. I think the problem is with the redis because fushall will solve the problem. I don't want to do flushall every time I add a task. Any idea? someone ever had a similar problem? Thanks. -
Is making a separate table with product categories, even though I have separate tables for products, a good idea?
I don't know which database schema is better to use. The first one seems nicer to me, because I don't know if making separate tables for categories if our table is that category is a good idea. But the second one makes it easier to query the database. Unless other options are better, I will try all the advice. First: class Genre(models.Model): CATEGORY_CHOICES = (('book', 'Book'), ('cd', 'CD'), ('film', 'Film'),) name = models.CharField(max_length=100) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) def __str__(self): return str(self.name) + " " + str(self.category) class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) class CD(Product): band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) class Film(Product): director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) Second: class Product(PolymorphicModel): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', … -
Django 4.0 Dynamically adding a new form
I am trying to add a form to a new row in there own columns with a button then having all the forms saved with the submit button. Only the first form is being saved, I am assuming it is the javascript doing it but I have no clue with javascript and ChatGPT is not helping lol {% extends 'containers/base.html' %} {% block body %} <h3 class="m-4">All Containers</h3> <div class="row"> <div class="col-12"> {% if success %} <div class="alert alert-success" role="alert"> Container/s have been added successfully. <a href="{% url 'index' %}" class="alert-link">Go to Home Page.</a> </div> {% else %} <div class="card bg-light mb-3"> <div class="card-header">Add Containers</div> <div class="card-body"> <p class="card-text"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th scope="col">Company Name</th> <th scope="col">Container Number</th> <th scope="col">Driver In</th> <th scope="col">Date In</th> <th scope="col">Driver Out</th> <th scope="col">Date Out</th> <th scope="col">Container Size</th> <th scope="col">Empty/full</th> <th scope="col">Import/Export</th> </tr> </thead> <form action="{% url 'add' %}" method="POST"> {% for form in formset %} {% csrf_token %} {{ formset.management_form }} <tbody class="container-table-body" id="container-table-body"> <tr> <td> <div class="fieldWrapper"> {{ form.company_name }} </div> </td> <td> <div class="fieldWrapper"> {{ form.container_number }} </div> </td> <td> <div class="fieldWrapper"> {{ form.driver_in_name }} </div> </td> <td> <div class="fieldWrapper"> {{ form.driver_in_date }} </div> </td> <td> <div class="fieldWrapper"> … -
Admin not giving permission to newly registered user unless he/she is approved by him
Iam creating a school management website, there are three modules : admin,teacher and student. The registered teacher and student can only log into the website after admin approves them. For That here iam using a status field in both teacher and student model as intergerfield and setting its default value as 0. so after registration teacher and student have status 0 and when the admin approves them the status value changes to 1 and then they can log in. models.py => rom django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Login(AbstractUser): is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Course(models.Model): course_name = models.CharField(max_length=100) course_desc = models.TextField(max_length=200) def __str__(self): return self.course_name class teacher(models.Model): user = models.ForeignKey(Login, related_name='Teacher', primary_key=True, on_delete=models.CASCADE) Name = models.CharField(max_length=100) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) Course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) Email = models.EmailField() Image = models.ImageField(upload_to='images/teachers') Status = models.IntegerField(default=0) def __str__(self): return self.Name class student(models.Model): user = models.OneToOneField(Login, on_delete=models.CASCADE, related_name='Student', primary_key=True) Name = models.CharField(max_length=100) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) Course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) Email = models.EmailField() Image = models.ImageField(upload_to='images/students') Status = models.IntegerField(default=0) def __str__(self): return self.Name and the forms.py=> from … -
Celery worker keeps creating new SQS queue
I'm using Django with Celery and attempting to deploy Celery using SQS and ECS. These are my celery-related Django settings: CELERY_BROKER_URL = "sqs://" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_IMPORTS = "app.tasks" CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-west-2", "predefined_queues":{ "staging.fifo": { "url": "https://sqs.us-west-2.amazonaws.com/<account id>/staging.fifo", } } CELERY_TASK_DEFAULT_QUEUE = "staging.fifo" My celery worker ECS task definition gives it full IAM access to SQS. But every time I start my celery worker ECS container, instead of using my existing SQS queue, "staging.fifo," the worker seems to create a new queue in SQS called "celery." Why is it creating this new queue instead of using the queue that I specified? -
Django admin dependable dropdown
So I'm trying to make a dependable dropdown for django admin, and when i select a province the console shows the following error: 405 method not allowed {"readyState":4,"responseText":"{\"detail\":\"Method \\\"GET\\\" not allowed.\"}","responseJSON":{"detail":"Method \"GET\" not allowed."},"status":405,"statusText":"Method Not Allowed"} the related codes are as given below and the method is POST on both the ajax function and View but it says GET method is not allowed the models.py is as: class Province(models.Model): name = models.CharField( max_length=30 ) class Meta: verbose_name = _("province") verbose_name_plural = _("provinces") def __str__(self): return self.name class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("district") verbose_name_plural = _("districts") def __str__(self): return self.name class SchoolProfile(models.Model): """ School detail model """ .....other_fields.... province = models.ForeignKey( Province, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("province") ) district = models.ForeignKey( District, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("district") ) and on admin.py @admin.register(SchoolProfile) class SchoolProfileAdmin(admin.ModelAdmin): inlines = [ServerInline, ServerUpdateInline] list_display = [...] class Media: js=("school/dependent-dropdown-ajax.js",) views.py from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from django.http import JsonResponse class DistrictList(APIView): permission_classed=[IsAuthenticated,] def post(self, request, format=None): province=request.data['province'] district={} if province: districts=Province.objects.get(id=province).districts.all() district={p.name:p.id for p in districts} return JsonResponse(data=district, safe=False) urls.py url(r'^districts/$', DistrictList.as_view(), name='districts'), dependent-dropdown-ajax.js the …