Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading a .YAML file using Django and reading it's contents to display a graph/plot on the webpage
I want to be able to upload .yaml files using the Django Admin interface and then access the content of that file to do preprocessing and outputting a graph using plotnine on the webpage. Example code of preprocessing and plotting a graph: import yaml import pandas as pd import numpy as np import plotnine as p9 slurm_data = {} with open('slurm-22.05.5-02_27_2023-16_33_29.yaml', 'r') as f: all_slurm_data = yaml.load_all(f, yaml.FullLoader) for d in all_slurm_data: for k,v in d.items(): slurm_data[k] = v time_window = 60 data_frames = [] for slurm_partition_name, slurm_partition_data in slurm_data.items(): data_frames.append(pd.DataFrame.from_dict(slurm_partition_data)) data_frames[-1]['node_type'] = slurm_partition_name data_frames[-1]['days_scheduled'] = np.random.randint(0,time_window, size=len(data_frames[-1])) data_frames[-1]['days_free'] = time_window - data_frames[-1]['days_scheduled'] data_frames[-1]['projected_utilization'] = data_frames[-1]['days_scheduled'] / float(time_window) slurm_data_frame = pd.concat(data_frames) slurm_data_frame.hist(bins=30) -
configure Django settings for static files with Heroku
I am trying to deploy my Django website using Heroku. So far the site has deployed successfully but the only problem is collecting the static files. I am stuck with how I am supposed to configure my settings.py file so that the website knows where to find these static files. folder structure -website ---App ------Static ---------App ---Website ---staticfiles ---manage.py ---Procfile ---requirements.txt ---runtime.txt settings.py DEBUG = False BASE_DIR = Path(__file__).resolve().parent.parent MIDDLEWARE = [ ... "whitenoise.middleware.WhiteNoiseMiddleware", ... ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "App/static") ] django_heroku.settings(locals()) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" error msg whitenoise.storage.MissingFileError: The file 'App/static/app/styling-images/search_button.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000016932C5D190>. The CSS file 'App\styles.css' references a file which could not be found: App/static/app/styling-images/search_button.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. -
How to Create data with read_only_fields in Django Rest Framework
and facing a issue with read_only fields suppose I have the follwoing serailizer `class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] read_only_fields = ['account_name']` where the account_name (in the Account model this field can not be null) is set to read_only because I do not want to update its data after creation but while creating the data using I am passing the account_name in the serializer but its excluding the account_name and giving the error "account_name" can not be null can anyone give me the solution for this how I can create a data with read_only field which can not be null I have tried to remove it from read_only_field but by doing this the account_name can be update but I don't want to update it after creation -
How to update status of Celery's tasks in Django?
Friends I have a question: I want to update the status of celery's tasks in Django. An example of what I want: 1- Create a task in tasks say to extract numbers from multiple text files: @shared_task() def text_analysis(): #Do this and that 2- Create a function in views to upload the files: def text_analysis(request): if request.method == 'POST': text_files = request.FILES.getlist("files") for text in text_files: text_analysis.delay() return render(request,"demo_demo.html",{"files":files}) 3- Create a HTML template to view the results: <main> <form method = "POST" enctype = "multipart/form-data" id = "texts_form"> {% csrf_token %} <input name="files" type = "file" multiple > <button type = "submit"> Submit </button> </form> <div class="table-data"> <div class="order"> <div class="head"> <h3>Recent Text Files</h3> </div> <table> <thead> <tr> <th>Name</th> <th>Creating Date</th> <th>Status</th> </tr> </thead> <tbody> <div> {% for file in files %} <tr> <th> file name </th> <th> file status. ->>>>>>>>>> What I want to do!!!! </th> </tr> {% endfor%} I tried many methods like the following: https://github.com/IbrahemKandel/python-dontrepeatyourself-django-celery-result-backend/blob/main/core/templates/home.html https://github.com/testdrivenio/fastapi-celery/blob/master/project/static/main.js -
504 Gateway Timeout in Kubernetes Deployed Django Application with Nginx Ingress
I am facing a 504 Gateway Timeout issue with my Django application deployed on Kubernetes. The application is running behind an Nginx ingress controller. My longer running requests keep timing out after 1 minute exactly. I'm not sure what could be causing the issue as i've altered the timeouts. My Ingress resource has the following annotations: Annotations: ingress.kubernetes.io/proxy-body-size: 100m ingress.kubernetes.io/proxy-connect-timeout: 1000 ingress.kubernetes.io/proxy-read-timeout: 1000 ingress.kubernetes.io/proxy-send-timeout: 1000 ingress.kubernetes.io/send-timeout: 1000 ingress.kubernetes.io/uwsgi-read-timeout: 1000 Additionally, I have the following Nginx ConfigMap settings: allow-snippet-annotations: "true" client-max-body-size: 100m hsts-max-age: "1" max-fails: "100" proxy-buffering: "off" proxy-connect-timeout: 610s proxy-read-timeout: 600s proxy-send-timeout: 300s uwsgi_connect_timeout: 600s worker-shutdown-timeout: 86400s I run Django using gunicorn like this: /usr/local/bin/gunicorn config.wsgi -w 2 -b 0.0.0.0:5000 --chdir=/app --timeout 1000 --limit-request-line 0 The application works fine locally and doesn't have any performance issues. I have tried increasing the timeouts and resources for the application, but the issue persists. I would appreciate any suggestions on how to resolve the 504 Gateway Timeout error or any tips on how to further debug this issue. -
acess services.py from a model Manager
I created a services.py file on the root directory of an app called mymoney and I plan to add helper functions there to keep my models.py file with simpler language. Now I wonder, how can I access functions and methods inside the services.py from the a model Manager? models.py from django.db import models from datetime import date class Balance(models.Model): date = models.DateField(auto_now_add=True) account = models.ForeignKey('mymoney.account', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=15,decimal_places=2) objects = BalanceManager() class Meta: app_label = "mymoney" Manager (a continuation of models.py, that's why no imports) class BalanceManager(models.Manager): def balance_inconsistences(balance_dates: dict, initial_date: date, today: date) -> tuple: # return tuple with two lists: return of first wrong_balance_dates() # and second return of dates_missing_balance_consolidation() wrong_dates = wrong_balance_dates(balance_dates, initial_date) dates_missing = dates_missing_balance_consolidation(balance_dates, initial_date, today) return wrong_dates, dates_missing services.py from mymoney.models import Balance from datetime import date from calendar import monthrange def end_month_dates_since_first_transaction(initial_date: date, today: date) -> list: pass def wrong_balance_dates(balance_dates: dict, initial_date: date) -> list: pass def dates_missing_balance_consolidation(balance_dates: dict, initial_date: date, today: date) -> list: pass -
django 4: type object 'Post' has no attribute 'published'
database is ok, migrations created problems with it **object_list = Post.published.all() ** Post: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') Views: def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) Migrations: class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(max_length=250, unique_for_date='publish')), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=10)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to=settings.AUTH_USER_MODEL)), ], ), ] urls main app: urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^blog/', include(('blog.urls', 'blog'), namespace='blog')), ] urls blog app: urlpatterns = [ # post views re_path(r'^$', views.post_list, name='post_list'), re_path(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] first time per stack overflow, sorry for the mistakes registered in the database column "published". idk what's the problem -
Field 'id' expected a number but got 'filter_data'. DJANGO, AJAX
I am working on filters in my project. Based on the tutorial, I started adding Ajax so that I could filter cards by several categories. Everything was working fine until I added the data and jsonResponse. Now every time I click the checkbox I get this error Ajax $(document).ready(function(){ $(".axaLoader").hide() $(".filter-checkbox").on('click', function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this). val(); var _filterKey=$(this). data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'filter_data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ console.log(res); $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); }); }); views.py def filter_data(request): return JsonResponse({'data':'hello'}) urls.py from django.urls import path, include from django.contrib.auth.views import PasswordChangeView from . import views from .forms import PasswordUpdateForm urlpatterns = [ path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('registration/', views.registrationPage, name="registration"), path('profile/', views.profile, name="profile"), path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"), path('change_password/profile/', views.profile, name="profile"), path('update_item/', views.updateItem, name="update_item"), path('update_wish_item/', views.updateWishItem, name="update_wish_item"), path('process_order/', views.processOrder, name="process_order"), path('<str:id>', views.product_view, name="product_view"), path('wishlist/', views.wishlist, name="wishlist"), path('search/', views.search, name="search"), path('filter_data/', views.filter_data, name="filter_data"), path('search/<str:id>',views.product_view, name="product_view"), ] Error Traceback (most recent call last): File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\PythonProject 555\boots\store\views.py", line 118, in product_view product = Product.objects.filter(id=id).first() File … -
Failed to save Django formset with queryset
i have faced the problem in django formset, i want to update formset using function view, when this line formset = MyFormset(request.GET or None, instance=form_main, queryset=queryset) included cant save but if i remove instance=form_main, queryset=queryset) it does not populate data but i can add manually and save it. I want this formset to polulate from database and to save it back to database view.py form_main = get_object_or_404(MyModel, pk = pk) queryset = MyFormset.objects.order_by('item') if request.method == 'GET': form = MainForm(request.GET or None, instance=form_lpo) formset = MyFormsetForm(request.GET or None, instance=form_main, queryset=queryset) elif request.method == 'POST': formset = Grn_LineItemFormset(request.POST) form = MainForm(request.POST) if form.is_valid(): newmodel= NewModel.objects.create(................) -
Need to add custom forms based on User input
So basically I need to implement the following functionality In my django project, the admin should be able to select number of fields he needs and their type(textfield, radio buttons, etc.., mandatory fields and non mandatory fields ) for his form and based on this a new page with a form which has the aforementioned fields should be rendered. The admin should be able to add this as a backend script in django model. I tried a way out via Model forms but couldn't get a clear layout as to how should i use it. I am fairly new to this techstack. Any guidance would be helpful Thanks -
Django metadata returns blank?
I want to apply some metadata to a stripe-checkout. No errors. When the payment is done without errors, I am not able to collect the metadata again. The returned data is just blank like this {}. The checkOutSission-view looks like this: @csrf_exempt def createCheckoutSession(request): if request.method == 'POST': data = json.loads(request.body) product = data[0] option_back = data[1] option_legs = data[2] option_length = data[3] # Create a Stripe Checkout session session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': product, 'description': (f'Back: {option_back} | Legs: {option_legs} | Length: {option_length}'), 'quantity': 1, 'metadata': { 'option_back': option_back, 'option_legs': option_legs, 'option_length': option_length, }, }, 'unit_amount': 300, # in euro }, }], mode='payment', success_url='http://127.0.0.1:8000/configurator/success/?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/configurator/cancel/', ) return JsonResponse({'session_id': session.id, 'checkout_url': session.url}) else: return JsonResponse({'error': 'Invalid request method'}) The view that schould be called after the payement looks like this: def success(request): session_id = request.GET.get('session_id') session = stripe.checkout.Session.retrieve(session_id) items = session.get('customer_details') print(items.email) values = session.get('metadata') print(values) # Gjør noe med produktinformasjonen return HttpResponse("Success") Why do it not work like my predictions? I have tried to move the "metadata-block" in diffrent levels of the session-data-blocks. Nothing makes the wanted results. -
Django - Can't fetch Json data in javascript
Hello I am pretty new to Django and Javascript I want to build a simple application where users can write posts and see a list of all posts in reverse chronologial order on the index page. (The index page is rendered fine.) I created some Posts via the admin interface. Unfortunately I can't figure out why I am not able to fetch the JsonResponse and no div gets append to my template. the code looks as following: first I've created a Posts model class Posts(models.Model): text = models.TextField(max_length=512) timestamp = models.DateTimeField(auto_now=True) def serialize(self): return { "id": self.id, "text": self.text, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } My view function to get all posts from the datatbase is called via path("get_posts", views.get_posts, name="get_posts"), and looks like this: @login_required def get_posts(): # get all posts posts = Posts.objects.all() # Return posts in reverse chronologial order posts = posts.order_by("-timestamp").all() return JsonResponse([post.serialize() for post in posts], safe=False) In my Javascript file (index.js) I want to load all Posts, create a div for each post and append them to my template document.addEventListener('DOMContentLoaded', function() { // By default, load_posts load_posts(); }); function load_posts() { // get posts from /posts API Route fetch('/get_posts') .then(response => response.json()) .then(posts … -
django.contrib.auth import get_user_model
I get an error in my User AttributeError: type object 'User' has no attribute 'objetcs' I get the error in forms.py when I try to use my User. // forms.py // from django import forms from django.contrib.auth import get_user_model from django.db import models from . import models User = get_user_model() class PerfilForm(forms.ModelForm): class Meta: model = models.Perfil fields = '__all__' exclude = ('usuario',) class UserForm(forms.ModelForm): password = forms.CharField( required=False, widget= forms.PasswordInput(), label='Senha' ) password2 = forms.CharField( required=False, widget= forms.PasswordInput(), label='Confirmar senha' ) def __init__(self, usuario=None, *args, **kwargs): super().__init__(*args, **kwargs) self.usuario = usuario class Meta: model = User fields = ('first_name', 'last_name', 'username', 'password', 'password2', 'email',) usuario_db = User.objetcs.filter(username=usuario_data).first() **<-- here I get the error** email_db = User.objetcs.filter(email=email_data).first() -
Django rest framework- blog post comment delete permission for admin user and owner user
does anyone know how to set delete permisssion for commented owner to delete the comment and for the admin user, delete all comments Serializers.py class DeleteCommentSerializer(serializers.ModelSerializer): class Meta: model = CommentModel fields = '__all__' Views.py class CommentDeleteView(generics.DestroyAPIView): permission_classes = [IsAdminUser,IsOwner] queryset = CommentModel.objects.all() serializer_class = DeleteCommentSerializer def perform_delete(self, serializer): serializer.save(user=self.request.user) Permissions.py class IsOwner(BasePermission): def has_permission(self, request, view): if request.method in ['PUT','DELETE']: return True return False def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.user == request.user -
How do I write a Django query that searches a nested JSON array?
I have the following JSON object (named 'data') on my Draft model: DRAFT1 data= { communications = [ {name: "john"}, {name: "bobby"} ] } DRAFT2 data= { communications = [ {name: "mark"}, {name: "erin"} ] } I'm guessing this is vaguely correct for a query, but I can't figure out the syntax for the '*'? Draft.objects.filter(data__communications__*__name__in=['john', 'erin']).count() How can I write a Django/Postgres query to return DRAFT1 and DRAFT2 as the result? -
AWS lightsail deployment Errors django
Good day, I have built a python / django webapp that i'm ready to deploy. I'm trying to deploy my webapp using AWS Lightsail, but the problem i'm facing is that my webapp will not load. I'm receving the error as follows:, but on my local Visual Studio code, but webapp is working just fine. What am i missing? My settings code is -
Point custom domain to a different website Django
I have a Django project deployed to a ubuntu server from digital ocean, using Apache as the web server and mod_wsgi, a custom domain name from Namecheap, and an SSL certificate. It has everything needed to be a solid website. But I also have a flask app deployed on an EC2 instance from AWS, besides changing the name servers on NameCheap to point to my EC2 instance, what else should I do for my domain to point to my Flask app instead of my Django app? Is it just as simple as removing the domain name from ALLOWED_HOST in Django settings.py? or is this more complex now that I have an SSL certificate? I hope it's not a meaningless question. -
How can I filter the queryset to only display the just created assignment
I have a model form which creates assignments, and each assignment needs to have some criteria, and so the next page in the creation process is a model formset which lets the user create multiple criteria at once. The problem I'm currently having is that I only want the user to add criteria to the assignment that they have just created, rather than using the dropdown menu and selecting the assignment manually. I've read about modifying the queryset and it seems like the way to go but I',m not sure how I can get the value of just the newly created assignment. The models: # Assignment class Assignment(models.Model): assignmentName = models.CharField(max_length=100) def __str__(self): return self.assignmentName def get_absolute_url(self): return reverse('assignment-view') #Criteria class Criteria(models.Model): assignmentID = models.ForeignKey(Assignment, on_delete=models.CASCADE) criteriaDescription = models.TextField() def __str__(self): return self.criteriaDescription View: criteriaFormset= modelformset_factory(Criteria, fields=('assignmentID','criteriaDescription')) form = criteriaFormset() return render(request,'markingApp/createCriteria.html', {'form': form}) -
TOKEN_LIMIT_PER_USER in django rest knox is not working
Everything was working fine until I created a custom user for my django project and since then, time limit per user is no longer working but the expiry date for the token is working fine, I have been searching online to find any solution but I can find any so I'm stack and don't know how to go about it to fix it so I flush my database and do the makegrations and migrate again but none of them worked -
How to add clipboard module to QuillField() in django for using in django admin?
Copying and pasting are not handling correctly on the Quill Editor. Is there any additional instructions which are needed when using the QuillField() in django to properly enable it, specially for copying text documents with images? This is how I am doing it: class Post(models.Model): customer = models.ForeignKey(Customer,on_delete=models.DO_NOTHING,related_name='post_customer') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='posts_author') updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) asset = models.IntegerField(choices=POST_ASSET, default=0) status = models.IntegerField(choices=POST_STATUS, default=0) article = QuillField(blank=True, null=True) -
How would I perform post-setup init steps in Django?
Where would I put steps I'd like to perform AFTER Django's setup() call? I expected this would already be a Django signal (like post_migrate). It seems like making my own versions of get_wsgi_application, etc. with callbacks is the next best option. Since that code is rarely touched I can imagine that it could fail silently and no one would know why. For a little background, I'm making my own task runner on lambda using Django on Postgres. Being able to dynamically define scheduled python functions with their own arguments is a key feature. At start up, I need to connect database entries for functions and their definitions in code. The way I get around this problem today is at the image entrypoint: if not python_function_registry.is_registry_initialized(): python_function_registry.registry_setup() There are several places I do this today. It seems like there are several potential benefits to a post_setup signal (or something similar), so I expect it must already exist? Thanks for your help! -
why the @property django decorator doesn't work
I need to pass the 'def get_sale' method to the model in views to sort the products by get_sale, but after passing it an error comes out models.py @property def get_sale(self): '''Расчитать стоимость со скидкой''' price = int(self.price * (100 - self.sale) / 100) return price views.py class SortItems(GoodsHome):#сортировка товара def get_queryset(self): sort_types = { '0': '-time_create', '1': 'time_create', '2': 'get_sale', '3': '-get_sale', } sort_type = sort_types[self.kwargs['sort_type']] if 'query' in self.kwargs: query = self.kwargs['query'] return super(SortItems, self).get_queryset().filter(Q(artist__icontains=query) | Q(album__icontains=query)).order_by(sort_type) return super(SortItems, self).get_queryset().order_by(sort_type) -
Django Rest Framework Serializer giving error for Foriegn key field can not be null
I am working on a restframework api using DRF but while executing perform create its showing error for a foriegn key field "can not null" Serializer : `class StyleEditProductSerializer(ModelSerializer): class Meta: model = StyleEditProduct fields = '__all__' read_only_fields = ('style_edit',)` Model : `class StyleEditProduct(BlankModel): product = fields.default_fk_field(Product, related_name='style_edits') sort_order = models.IntegerField(default=0) style_edit = fields.default_fk_field(StyleEdit) class Meta: unique_together = ('product', 'style_edit')` Views : `class StyleEditProductMultipleView(CreateAPIView): serializer_class = StyleEditProductSerializer def create(self, request, *args, **kwargs): style_edit = get_object_or_404(StyleEdit, id=self.kwargs.get('style_edit_id')) style_edit_products = [] for product in request.data['data']: product['style_edit_id'] = style_edit.id style_edit_products.append(product) print(style_edit_products) serializer = self.get_serializer(data=style_edit_products, many=True) serializer.is_valid(raise_exception=True) try: self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)` Error : [{'sort_order': 1, 'product': 1, 'style_edit_id': 2}] (1048, "Column 'style_edit_id' cannot be null") I am not able to understand I am passing the data for the style_edit_id in the serializer but still giving the error, Can anyone help me in this I have tried to check in model and in serializer but I am facing this issue and I can't understand why its giving error -
Django admin restrict max inline forms by parent field
I have the following two models in Django. Model Contest has questions and Questions is another django model: class Contest(models.Model): min_questions = models.IntegerField() class Question(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name="questions") question = ... Then I add the questions as an inline in the contest admin: class QuestionInlineForm(forms.ModelForm): class Meta: model = Question fields = \['question'\] class QuestionInline(NestedStackedInline): model = Question form = QuestionInlineForm extra = 1 inlines = \[AlternativeInline\] #Igonre this class CustomContestAdmin(NestedModelAdmin): inlines = \[QuestionInline,\] This let me create the questions inside the contests form, the problem is that I want to restrict the number of questions to create using the field min_questions of the Contest model, so that the form doesn't let me create a contest if the total amount of questions is less than the field min_questions. Is there a way to achieve this? I'm using the nested_admin library and I tried the method clean but the questions count shows as 0 because the questions have to be added after the instance of contest is created. I think this could be done by using transactions so I can create the Contest, then add the questions and before saving to the database check if the questions count is … -
Dynamic background change depending on the incoming link
I'm currently writing a site in django and I want to create a dynamic link page where the background depends on what comes from the link. I know I can make templates for each background, but I have over 500 of them, so this method seems inappropriate. Is there a better way to do it? I tried join static and dinamic paths and also send prepared path from backend but this both and some other way were unsuccessful at least in my code