Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need to open a modal if a condition is satisfied and get the post value. Is this possible in django?
In my app there are several if conditions. In one of the if condition a modal with two buttons will be shown. if the user clicks one button it should go execute a statement. If user clicks another one it should execute another statement. Is it possible in django. In my views.py def something(request): if statement: (modal should pop up in window) and from the post value from the modal another process should be done. -
Django. Pytest and Postman are getting different results on a single default value when testing
I'm starting to get into Django and pytest. I created a project with few basic components, and it all works well as designed. Except for a Pytest result The model is: class Opportunity(models.Model): class OpportunityQualityLevel(models.TextChoices): H = "High" M = "Medium" L = "Low" class StageProbability(models.TextChoices): A = "Signed Contract" B = "Verbal Confirmation" C = "Resumes First" D = "Nothing Firm" name = models.CharField(max_length=60) value = models.IntegerField() quality = models.CharField(max_length=8, choices=OpportunityQualityLevel.choices, default=OpportunityQualityLevel.M, blank=True) Stage = models.CharField(max_length=24, choices=StageProbability.choices, default=StageProbability.D, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) is_active = models.BooleanField(default=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Opportunities" def __str__(self): return self.name The Serializer is: class OpportunitySerializer(serializers.ModelSerializer): class Meta: model = Opportunity fields = ["id", "name", "value", "quality", "Stage", "client", "is_active", "date_created", "last_updated"] The view is: class OpportunityViewSet(ModelViewSet): queryset = Opportunity.objects.all().order_by("name", "client", "-is_active") serializer_class = OpportunitySerializer pagination_class = PageNumberPagination The URL is: router = routers.DefaultRouter() router.register("", views.OpportunityViewSet) urlpatterns = [ path("", include(router.urls)) ] The test itself is very simple: Creating a client and assigning an opportunity from that client. The problematic field on value is the "is_active" I configured it in the model to be "True" as can be seen in the model. When testing with Postman … -
How to allow a user to add objects in Django admin based on the user that has logged in
I want to have an admin where any user who logs in to the admin dashboard can add the objects from their operator email only. Now, the user can add a package object from another operator email as well. I don't want a user to add objects under the email of another operator's email. My Models: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) user_type = models.CharField(max_length=1, choices=USER_TYPES, default='g') first_name = models.CharField(max_length=255, default="") def __str__(self): return self.user.email class Package(models.Model): operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) city = models.CharField(max_length=255) My package/admin.py: class PackageAdmin(ModelAdmin): icon_name = 'explore' autocomplete_fields = ['destination'] list_display = ('package_name', 'featured', 'price', 'discounted_price', 'savings', 'fix_departure', 'rating', 'date_created',) def get_queryset(self, request): abc = super(PackageAdmin, self).get_queryset(request) if request.user.is_superuser: return abc else: operator = request.user.profile return abc.filter(operator=operator) Here in the above image we can see that a user can add an object under another operator's email as well. I dont want that. The two solutions will be: Only the current user/profile visible in operator field. Although the emails are visible, cant add the package under another operator's ema -
Multi-image is my motive in this project. I wants to show images but not able to show them on front-end but able to upload multi-image on admin panel
My project is based on the multi-image there is problem with html file. There is some mistakes with the html file please help to find the problem in it. I am able to upload the images but they are not able to show on the frontend. help me in my project. my html files are thus: base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> blog.html {% extends 'base.html' %} {% block content %} <div class="row row-cols-1 row-cols-md-2"> {% for post in posts %} <div class="col mb-4"> <div class="card"> <div class="view overlay"> <img class="card-img-top" src="{{post.image.url}}" alt="Card image cap" > <a href="#"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body"> <h4 class="card-title">{{post.title}}</h4> <p class="card-text">{{post.description}}</p> <a href="{% url 'detail' post.id %}" class="btn btn-primary btn-md">Read More</a> </div> </div> </div> {% endfor %} </div> {% endblock %} detail.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 … -
Django GraphQL Testing Images
I'm currently performing pytest to test my GraphQL mutations. In this case, I input a test image file to determine if it's working. The following is a sample test in which the SimpleUploadedFile object throws a not JSON serializable error. What could be the cause and how should I fix this? @pytest.mark.django_db class TestUploadImage: query = """ mutation uploadImage($input: Upload!) { uploadImage(file: $input) { __typename ... on ResponseErrors { errors { __typename code message } } ... on Output { url } } } """ file = SimpleUploadedFile( name='test_image.jpg', content=b'', content_type='image/jpeg' ) input_data = {"file": file} def test_non_authenticated_request(self, user, client, client_query): response = client_query( self.query, op_name="uploadMessageImage", input_data=self.input_data, ) # Verify that there were no unhandled exceptions content = json.loads(response.content) assert "errors" not in content # Verify that AuthenticationError is in the response data assert AuthenticationError.__name__ in str(response.content) -
cart_id = self.request.session.get("cart_id", None)
I'm creating a ecommerce website with watching YouTube tutorial. Meanwhile typed this code cart_id = self.request.session.get("cart_id", None) Now I do not understand why this code. So plz explain usage of this code. if you have any issue to explain please mention link how that says this code. views.py class AddToCartView(TemplateView): template_name = "add_to_cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) product_id = self.kwargs['pk'] produc_obj = Product.objects.get(id=product_id) cart_id = self.request.session.get("cart_id", None) # Old Cart if cart_id: cart_obj = Cart.objects.get(id=cart_id) prd_in_this_cart = cart_obj.cartitem_set.filter(product=produc_obj) # Item already exist in cart if prd_in_this_cart.exists(): cartproduct = prd_in_this_cart.last() # first() prd_in_this_cart.quantity += 1 cartproduct.total += produc_obj.amazon_rate cartproduct.save() cart_obj.total += produc_obj.amazon_rate cart_obj.save() # Item already exist in cart else: cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() # New Cart else: cart_obj = Cart.objects.create(total=0) self.request.session["cart_id"] = cart_obj.id cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() return context -
My Custom mixin is not being called in my DetailView in Django?
My custom mixin is not being called in my DetailView. I have 2 DetailView which inherited same custom mixin but only one DetailView can inherited the mixin. Can you take a look and tell me what are my problems? # my custom mixins class GetLastestPostsMixin(object): model = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context # First Detail view class FirstDetailView(GetLastestPostsMixin, DetailView): model = Model1 template_name = my template def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context # Second DetailView class SecondDetailView(GetLastestPostsMixin, DetailView): model = Model2 template_name = my template def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context When I do .__mro__ in shell it shows me like this >>> FirstDetailView.__mro__ (<class 'my_app.views.FirstDetailView'>, <class 'my_app.views.GetLastestPostsMixin'>, ....) >>> SecondDetailView.__mro__ (<class 'my_app.views.SecondDetailView'>, ....) # custom mixin is not being called -
How to make docker-compose django server run on local wifi network, so our iOS developer can test the API from the iPhone device?
I'm trying to serve django on our local wifi IP, so our client developer can use his iOS device to test the API. The problem is that when I run the containers, it's only accessible from my chrome browser as localhost(=chrome browser run on the same macbook that is used to run the containers) My docker-compose file: version: '3' volumes: dev_postgres_data: {} dev_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/dev/django/Dockerfile image: apps_dev_django container_name: django depends_on: - postgres volumes: - .:/app:z env_file: - ./.envs/.dev/.django - ./.envs/.dev/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: apps_production_postgres container_name: postgres volumes: - dev_postgres_data:/var/lib/postgresql/data:Z - dev_postgres_data_backups:/backups:z env_file: - ./.envs/.dev/.postgres # ports must be set to use postgres container alone ports: - "5432:5432" If I run the django server locally(=not using docker-compose)with the command python manage.py runserver 192.168.0.255:8000, the client who is using the same wifi as me can access the API. I got the 192.168.0.255 with the command ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\ -f6(something I got after some googling). If I run ifconfig, I get, ... en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=400<CHANNEL_IO> ether a4:5e:60:f1:cb:5b inet6 fe80::85:51dd:e37a:5435%en0 prefixlen 64 secured scopeid 0x4 inet 192.168.0.17 netmask … -
Django getlist getting null
Hello guys im currently learning on how to send data from HTML to Django backend using Ajax. I have this HTML <div class="form-row"> <input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1"> <input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2"> <input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2"> <input id="submit-car" type="button" value="Submit"> </div> and then to send the data i use this code (Ajax) $('#submit-car').click(function () { const data = {user_id: user_id} $.ajax({ type: 'POST', url: '/submit-car/', data: data, beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", csrftoken); }, success: function (data) { $('#submit-form-field').prop('disabled', true); location.reload(); alert("Submit OK!"); } }); }); and then on the Django side i try to get the checked checkbox def insert_car_to_db(self, request): cars = request.POST.getlist('car-checkbox[]') print(cars) Weirdly enough when i try to get the checked data, i keep getting [] value, where did i miss ? am i misunderstand something? P.S i followed this post How to get array of values from checkbox form Django -
Django RestFramework JWT Token: Get User DoesNotExist error
After a user is deleted, the tokens on the client side are still valid until the time has expired. The issue is django restframwework does not handle a request from a deleted user and causes a 500. How can I prevent this? aceback (most recent call last): File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/lib/python3.6/site-packages/rest_framework/views.py", line 493, in dispatch self.initial(request, *args, **kwargs) File "/lib/python3.6/site-packages/rest_framework/views.py", line 410, in initial self.perform_authentication(request) File "/lib/python3.6/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/lib/python3.6/site-packages/rest_framework/request.py", line 220, in user self._authenticate() File "/lib/python3.6/site-packages/rest_framework/request.py", line 373, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 33, in authenticate payload = jwt_decode_handler(jwt_value) File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 105, in jwt_decode_handler secret_key = jwt_get_secret_key(unverified_payload) File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 26, in jwt_get_secret_key user = User.objects.get(pk=payload.get('user_id')) File "/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/lib/python3.6/site-packages/django/db/models/query.py", line 431, in get self.model._meta.object_name -
Grouping by date intervals of multiple datetime columns
I have a queryset that I want to group by months, quarters, and years. However, instead of just grouping based on one datetime field of a model, I would want to group by several datetime fields. E.g., I have sign ups for multiple event types (different models) and each of them has a date associated with the sign up. Now, I would like to find how many sign ups I have in total for each month. I used Coalesce(TruncMonth(x), TruncMonth(y), TruncMonth(z)) but that only groups on the first none null field. Is there any other way? -
How to connect android application with django?
I’m making an android app where I’m going to collect sensor data from the android phone and send a collection of data for machine learning model prediction. I have prepared a jupyter notebook for model fitting. How do I connect the android application with Django local server? -
django python has_change_permission for handling DATA_UPLOAD_MAX_NUMBER_FIELDS
I have a questions related about Django Python I'm having problems error of The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. I have red some of the documentations that I need to change / add in settings.py DATA_UPLOAD_MAX_NUMBER_FIELDS to 10240, but i think it won't solve of my problems. on my model, I have Inline models which related one to many, and they can't be modified, but how about if i add permission has_change_permission to false? will the inline value still sent to the server? thanks before -
How do i Fix django.db.utils.DatabaseError
How do i fix Django Database error. I'm using MongoDB with Djongo. Everything was working fine until recently when i decided to add NewApp. Whenever i try to migrate it greets me with django.db.utils.DatabaseError . I tried reseting the DataBase Manually as well as from Terminal but had no luck. I think it's super simple but imm new to Django and MongoDB can't seem to figure out how to fix it, any help will be greatly appreciated. Here's what the error looks like. Not implemented alter command for SQL ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL Applying articles.0002_article_author...Traceback (most recent call last): File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 783, in __init__ self._query = self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 875, in parse raise e File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 435, in parse self._add(statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 598, in _add raise SQLDecodeError(err_key=tok.value, djongo.exceptions.SQLDecodeError: Keyword: int Sub SQL: ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT … -
Django, Many-to-one relationship with Abstract entities
Say object contains multiple types of objects (Models) in an array, like a Page, that could contain a Post, Blog, Picture, in any quantity or order, where the user scrolls down and sees the following element and that depending on the page, is next element one of these types of elements. Thus a Page could contain: A Post A Post A Picture Or something pretty different such as: A Picture A Blog A Picture An element could be an abstract entity that has an attribute as a ForeignKey relating itself with Page, and its inheritance would gain access to that relationship: class Page(models.Model): ... class PageElement(models.Model): page = models.ForeignKey(LandingPage, verbose_name="Page", on_delete=CASCADE) class Meta: abstract = True class Post(PageElement): ... class Blog(PageElement): ... class Picture(PageElement): ... With this approach, you can serialize Page with a REST serializer, but you wouldn't have access to an pageElement_set, instead you would need to call post_set, blog_set, picture_set and loose the order of the objects. The question is: How do you implement such relationships in Django? So that you can have an order set of PageElement instances, and be able to have the desired order. -
Django: Do i have to restart celery beat, celery worker and Django gunicorn when new changes are uploaded to production server
I have a production server running Django application Django server is run using gunicorn and nginx pipenv run gunicorn --workers=1 --threads=50 --bind 0.0.0.0:8888 boiler.wsgi:application celery worker is run using pipenv run celery -A boiler worker celery beat is run using pipenv run celery -A boiler beat Now i have updated my model and few views on my production server (i.e pulled some changes using github) Now inorder to reflect the changes should i restart all celery beat,celery worker and Django server gunicorn or only celery worker and Django server gunicorn is sufficient or only Django server gunicorn is sufficient -
Django REST on Local Network
I know this is probably not the best place to ask but I can't seem to find a better one so here goes... I want to set up a local system using DJango REST and react.js/native as the UI for accessing the API on the same network e.g. a tablet which is fed a PWA would be fine. The server exists in-house and I do not want it connected to the web. Is it possible to deploy a production site from a local server and have it accessed only locally? It seems like it should be possible. If it is, how do you go about handling Https/SSL? I see self-signed certs but everywhere says not to use them on a production system. Can someone give me advice on how I can make this secure/possible? Edit: I should add that I would want to use Apache web server. -
Query a data in legacy mysql table views in django
I would like to connect in my legacy mysql view using django, but the models read tables only, how can i query in a mysql view using django models and orm? I tried something like this, here is my models.py from django.db import models class VwFullDetailBi(models.Model): control_no = models.CharField(max_length=50) fname = models.CharField(max_length=50) mname = models.CharField(max_length=50) lname = models.CharField(max_length=50) birthday = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'vw_fulldetail_bi' my serializers.py from rest_framework import serializers from .models import VwFullDetailBi class DetailsSerializer(serializers.ModelSerializer): class Meta: model = VwFullDetailBi fields = '__all__' and my views.py from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.generics import get_object_or_404 from .models import VwFullDetailBi from .serializers import DetailSerializer @api_view(['GET']) def farmerDetails(request): control_no = request.GET.get("control_no") details = VwFullDetailBi.objects.using("other_db").filter(control_no=control_no) detailSerializer = DetailSerializer(details, many=True) return Response(detailSerializer.data) I got this error and i know that perhaps the models treating it as table and not as view. (1146, "Table 'other_db.vw_fulldetail_bi' doesn't exist") -
How to generate multiple Dash App (and URLs) programmatically?
I have a simple Dash app with a choropleth map along with a simple dropdown. The data is sourced from a pandas dataframe and contains a few different metrics for each US state. I'd like to reproduce this standard layout for each of the US state but here's the problem: I'd like to avoid having to create 50 different dash apps (it doesn't look really practical neither scalable) I don't want to have a dropdown for users to select the state: the goal is to have multiple URLs, one for each state (mostly for search engine purposes). I was thinking of passing the US state as a URL parameter: I'd use this variable to filter the dataframe (limiting the dataframe scope will automatically make the choropleth zoom to the relevant state). However this is problematic since: Dash doesn't allow to set a default base URL for the app (at least as far as I could tell) The df cleaning/filtering happens before I can call the flask instance in Dash (this would be easily solvable though) as well as the app URL. I wanted to do this all within Dash for practicality but I guess I'd need to rely on Flask/Django … -
Django Allauth integration with Django CMS
I'm using DjangoCMS and AllAuth on a website I'm working on - I'm trying to get Django CMS to automatically send you to AllAuth's login page, instead of it's own admin page. Here's my current urls.py file: urlpatterns = [ path("sitemap.xml", sitemap, {"sitemaps": {"cmspages": CMSSitemap}}), path('en/accounts/', include('allauth.urls')), ] urlpatterns += i18n_patterns(path("admin/", admin.site.urls), path("", include("cms.urls"))) The issue is that DjangoCMS, when it's grabbing the admin page to show, using namespacing to get admin:login. Now, my thought was I can just have the namespace admin refer to AllAuth - but AllAuth doesn't support namespacing. Is there any way to either: Have that automatically redirect to AllAuth? I'd think it might be possible to have the default admin's page redirect in the view itself, but I'd rather not try to change the built in Django code Have that namespace get sent to a specific URL, even if AllAuth doesn't support it by default. Thanks! -
send_mail() missing 1 required positional argument: 'recipient_list'
Why i am receiving this error? send_mail() missing 1 required positional argument: 'recipient_list' did i miss something? from django.core.mail import send_mail from django.template import Context, loader def contact(request): .... email_template = loader.get_template('accounts/print.html') send_mail(email_template, [settings.EMAIL_HOST_USER], Email, fail_silently=False) -
GenericViews - and pushing model name in URL
using Django Generic CreateView - is it possible for me to pass a value into the CreateView from the URL call, that defines which model/table to base the view on? I did try get_context_data but believe that is not the solution, as I think it only pushes it to the rendered template. You will see from my scripts - I am pushing the value 'syslog_policy' - i would like the view to set the model variable to be, what-ever value I push from the URL. The reason for this, I have some pages/models that are similar - so rather than create multiple html pages and views - I wouldn't need to if I could get this to work. URL Call <li><a href="{% url 'security_app:HardenTemplateCreate' 'syslog_policy' %}">Update/Delete Policies</a></li> urls.py path('HardenTemplateCreate/<str:element>', HardenTemplateCreate.as_view(success_url="/security_tooling/add_success") ,name="HardenTemplateCreate") views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['element']= self.kwargs['element'] print(context['element']) return context model = !!<NEED VALUE SUPPLIED IN URL HERE>!! fields = ['name','template'] template_name = 'security_app/add.html'``` -
Generating audio files in a Django project template
I am attempting to create a pretty simple website using Django that will have a number of audio files stored in it and available for streaming and downloading. I know that there are other ways to do this, like using AWS, but I wanted to figure this way out first. I'll include my template here but wanted to note that it is currently messy because I have been experimenting with different structures to figure this problem out. {% for song in concert.song_set.all %} <li>{{ song.song_title }}</li> <li>{{ song.song_location }}</li> <!-- Working --> <audio class = "audioPlayer uniqueShowAP" controls <--controlsList="nodownload" src="{% static 'shows/audio/redRocks2019/01 Yi.mp3' %}"> Your browser does not support the <code>audio</code> element. </audio> <!-- Not Working...yet --> <audio class = "audioPlayer uniqueShowAP" controls <--controlsList="nodownload" src="/shows/static/shows/{{ song.song_location }}"> Your browser does not support the <code>audio</code> element. </audio> {% endfor %} What I want to happen is for every concert that I save it will go through the songs saved under that concert and add them to under the name of the song. I have each song's relative location saved in the data base so that I should be able to just call upon it's location. I've tested this out by calling … -
Django 3.1 bug: Reflexive Many-to-many relations. Add creates two relationships instead of one
in the model called Business: sold_at_businesses = models.ManyToManyField('self', db_table='businesses_to_sold_at_businesses', related_name='businesses_selling') test code - ms is a Business instance. ms.sold_at_businesses.clear() b = Business.objects.get(slug="test-business") if b: ms.sold_at_businesses.add(b) Bug: This single add call adds two entries to the pivot table. m -> b and b -> m Why are two connections being created when I clearly specify only one? this seems like a reflexive model bug in Django. -
How to set dynamic attributes in django rest framework serializers?
I have some json in the following format: { "daySchedules": { "500000004061582000": { "scheduleName": "Friday-Sunday", "services": [ { "name": "Lunch", "hours": { "startTime": "12:00:00.000", "endTime": "16:00:00.000" }, "overnight": false }, { "name": "Dinner", "hours": { "startTime": "17:00:00.000", "endTime": "23:00:00.000" }, "overnight": false } ], "openTime": "12:00:00.000", "closeTime": "23:00:00.000" }, "500000004061559163": { "scheduleName": "Tuesday-Thursday", "services": [ { "name": "Breakfast", "hours": { "startTime": "04:00:00.000", "endTime": "11:00:00.000" }, "overnight": false }, { "name": "Lunch", "hours": { "startTime": "12:00:00.000", "endTime": "16:00:00.000" }, "overnight": false }, { "name": "Dinner", "hours": { "startTime": "17:00:00.000", "endTime": "20:00:00.000" }, "overnight": false } ], "openTime": "04:00:00.000", "closeTime": "20:00:00.000" } }, "weekSchedule": { "monday": null, "tuesday": "500000004061559163", "wednesday": "500000004061559163", "thursday": "500000004061559163", "friday": "500000004061582000", "saturday": "500000004061582000", "sunday": "500000004061582000" } } The attributes in the json 500000004061582000 and 500000004061559163 is dynamic and determined by what's returned in the weekSchedule. I wish to create the following serializers: class ScheduleForDaySerializer(serializers.Serializer): schedule_name = serializers.CharField() services = serializers.ListField() open_time = serializers.CharField() close_time = serializers.CharField() class WeekScheduleSerializer(serializers.Serializer): monday = serializers.CharField(allow_null=True) tuesday = serializers.CharField(allow_null=True) wednesday = serializers.CharField(allow_null=True) thursday = serializers.CharField(allow_null=True) friday = serializers.CharField(allow_null=True) saturday = serializers.CharField(allow_null=True) sunday = serializers.CharField(allow_null=True) class DaySchedulesSerializer(serializers.Serializer): # what comes here? class SchedulesSerializer(serializers.Serializer): day_schedules = DaySchedulesSerializer() week_schedule = WeekScheduleSerializer() I'm struggling to determine how …