Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[DJANGO][II] Can't deploy application
I'm facing an issue with my Django Application Deployment. I have followed several tutorials ( lastly this one : https://www.youtube.com/watch?v=APCQ15YqqQ0) to help me deploy my application, I don't understand why my Handler is not working. Here is my web.config file : <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\xxx\documents\github\app_folder\scripts\python.exe|c:\users\xxx\documents\github\app_folder\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\Users\xxx\Documents\GitHub\app_folder\app" /> <add key="WSGI_HANDLER" value="app_name.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="app_name.settings" /> </appSettings> </configuration> As I have my virtualenv in the app_folder folder, app folder contains the Django project. I have this message for output : Additional information about the error : Module FastCgiModule Notification ExecuteRequestHandler Handler django_handler_test Error code 0x8007010b URL requested http://localhost:94/ Physical Path C:\Users\xxx\Documents\GitHub\app_folder\app Session opening Method Anonyme User Session Anonyme I translated the category name as they were in french -
How to have different change frequency and priority for a list of items in django sitemap?
I have built a static sitemap in my django project as below: class StaticViewSitemap(Sitemap): changefreq = "weekly" priority = 0.9 protocol = 'http' if DEBUG else 'https' def items(self): return ['home', 'contact_us', 'blog', ] def location(self, item): return reverse(item) What should I do if I want to set different priorities and change frequency for different urls? I have seen this question but I still ddo not know what to do: Priority issue in Sitemaps -
Server Error 500 when trying to add instance of a model on Django
I have a website working perfectly in Django for me, I can add and delete instances of models as I want. However, if someone else tries to add an instance with the exact same admin account, the page shows "Server Error 500". I am using the default SQLite settings for django. models.py: from django.db import models from datetime import datetime # Create your models here. class Receita(models.Model): titulo_receita = models.CharField(max_length=200); resumo_receita = models.CharField(max_length=255, default='') tempo_receita = models.CharField(max_length=200, default=''); rendimento_receita = models.CharField(max_length=200, default=''); imagem_preview = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png') conteudo_receita = models.TextField(); data_receita = models.DateTimeField('Data publicação', default=datetime.now()); def __str__(self): return self.titulo_receita; class Produto(models.Model): nome = models.CharField(max_length=200); desc = models.TextField() # desc = models.CharField(max_length=255, default=''); imagem = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png') info1 = models.CharField(max_length=255, default='', blank=True) cod1 = models.CharField(max_length=255, default='', blank=True) info2 = models.CharField(max_length=255, default='', blank=True) cod2 = models.CharField(max_length=255, default='', blank=True) info3 = models.CharField(max_length=255, default='', blank=True) cod3 = models.CharField(max_length=255, default='', blank=True) def __str__(self): return self.nome; admin.py: from django.contrib import admin from .models import Receita from .models import Produto from tinymce.widgets import TinyMCE from django.db import models # Register your models here. class ReceitaAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TinyMCE()} } admin.site.register(Receita, ReceitaAdmin) admin.site.register(Produto) -
ProgrammingError at / relation "products_product" does not exist LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_
Error: ProgrammingError at / relation "products_product" does not exist LINE 1: ...votes_total", "products_product"."hunter_id" FROM "products_... My views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): products = Product.objects return render(request, 'products/home.html',{'products':products}) @login_required(login_url="/accounts/login") def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url = request.POST['url'] else: product.url = 'http://' + request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) else: return render(request, 'products/create.html',{'error':'All fields are required.'}) else: return render(request, 'products/create.html') def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'products/detail.html',{'product':product}) @login_required(login_url="/accounts/login") def upvote(request, product_id): if request.method == 'POST': product = get_object_or_404(Product, pk=product_id) product.votes_total += 1 product.save() return redirect('/products/' + str(product.id)) My models.py: from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') urls.py: from django.urls import path, include from . import … -
Send values from URL to JavaScript
I don't know JavaScript yet, so I got a function online to create and delete new fields on my HTML page, but, I'd like to give it one more function, which I'm not able to do. Here's what I need: I'd like that at the same time I click on it to delete the input field, it would call a function view to also delete the data. To delete the data, I had to create a new link inside the HTML, which is not the best way. Is there a way to make it work? Here's the code. edit.html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'partials/_header.html' %} <style> a:link, a:visited{ color: #006600; } .btn-green{ background-color:#008000 ;color: #FFF; } .btn-green:hover{ color:#fff; background-color: #009900; border-color: #008000; } .btn-ico{ background-color:#008000; padding: 2px 5px; margin-bottom: 10; } textarea { height: 100px; } </style> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <!-- Begin page content --> <main role="main"> <div class="container mt-4"> <form enctype="multipart/form-data" action="" class="form-group" method="POST">{% csrf_token %} <div class="form-group"> {{ form.nome_projeto.label_tag }} {{form.nome_projeto}} </div> {{ form_colab.management_form }} <label>Colaboradores do Projeto:</label> {% for colab in form_colab %} {{ colab.non_field_errors }} {{ colab.errors }} {% for hidden in colab.hidden_fields %} … -
Django annotate using WHEN CASE
I have a question regarding annotation in Django, and inside the annotation I have CASE WHEN conditions, same as in the following example: queryset = queryset.annotate( title=Case(When(title_filter, then=Value("any text")), When(test_filter, then=F('name')), When(test1_filter, then=F('test__name')), output_field=CharField()), key=Case(When(title_filter, then=F('category__id')), When(test_filter, then=F('test_id')), When(test1_filter, then=F('test1__id')), output_field=CharField())) I want to annotate these fileds, title, key. But, we can see that for the each field is applyed the same condition, like Case(When(title_filter), When(category_filter)). There is a posiblity to apply the condintion just once and after that to apply the value for each field ? Like: if title_filter: title = Value("any text") key =then=F('category__id') elif test_filter: title = F('name') key = F('test_id') -
Getting error " Failed building wheel for twisted" while trying to install Django channels in windows10
I was trying to install Django channels but got error: ERROR: Failed building wheel for twisted Running setup.py clean for twisted Failed to build twisted Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error ERROR: Command errored out with exit status 1: The screenshot of terminal: How can I solve this problem? -
How to call django forms inlineformset into django templates
i am new to django and learning some from stackoverflow. Now i am creating a website for post with images and title. I found ways to connect my two models (images and post) at https://stackoverflow.com/a/62158885/13403211. it is working fine when i add post from admin. But i want to know how can i add those inlineformset fields into my template for user to fill in.Does anyone knows?? Here is the code i found. I copy the same code in my app to try. models.py class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="items") name = models.CharField(max_length=100) class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) img = models.ImageField(default="store/default_noitem.jpg", upload_to=get_image_dir) forms.py from django import forms from django.forms.models import inlineformset_factory from .models import Item, ItemImage class ItemImageForm(forms.ModelForm): class Meta: model = ItemImage exclude = () class ItemForm(forms.ModelForm): class Meta: model = Item fields = ["name",] ItemImageFormSet = inlineformset_factory( Item, ItemImage, form=ItemImageForm, fields=['img'], extra=3, can_delete=True # <- place where you can enter the nr of img ) views.py class ItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): template_name = "items/add_item_form.html" success_message = 'Item successfully added!' form_class = ItemForm def get_context_data(self, **kwargs): data = super(ItemCreateView, self).get_context_data(**kwargs) data['form_images'] = ItemImageFormSet() if self.request.POST: data['form_images'] = ItemImageFormSet(self.request.POST, self.request.FILES) else: data['form_images'] = ItemImageFormSet() return data def form_valid(self, form): … -
'+add' button doesn't work properly when django-ajax-select is used
In short: django-ajax-selects works fine with filtering existing items, but gives JS error by adding new item. Details. Using Django 3.1. At Admin site one needs to create object of model Choice with ForeignField to model Question. Django-ajax-selects (DAS) is used to populate the field (dynamic filtering). By typing letters DAS handles the queryset and outputs the list of relevant questions. One can choose a question from the list and save new Choice. All this works fine. If no proper questions by typing are found then one can click +add button and add new question in popup window with form. After clicking 'Save' according to DAS docs: new question must be saved into the database; popup window must be closed; the edited field must be populated with new question . Screenshot with popup window The problem is that Django stops at step2: new question is created, the popup window is getting blank and doesn't close with "Popup closing ..." in the head. There is an JS error in the window: Uncaught TypeError: window.windowname_to_id is not a function at window.dismissAddRelatedObjectPopup (:8000/static/ajax_select/js/ajax_select.js:194) at popup_response.js:13 The HTML-code of the blank page is <!DOCTYPE html> <html> <head><title>Popup closing…</title></head> <body> <script id="django-admin-popup-response-constants" src="/static/admin/js/popup_response.js" data-popup-response="{&quot;value&quot;: &quot;6&quot;, … -
After deleting my database and trying to apply a new migrations i get this errors that say django.db.migrations.exceptions.NodeNotFoundError
Am trying to apply a migration to a new database but I keep getting this error, I have deleted all migration files in my old database and also files in the apps. when I tried applying migrations to a new database or running python manage.py runserver then I get this error..? I wonder what might be the problem. am using Django 3.1.1 E:\All django project\Real-Estate-Django-Web-App-master>manage.py migrate Traceback (most recent call last): File "E:\All django project\Real-Estate-Django-Web-App-master\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Python38\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Python38\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Python38\lib\site-packages\django\db\migrations\loader.py", line 255, in build_graph self.graph.validate_consistency() File "C:\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Python38\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_user_following dependencies reference nonexistent parent … -
Template tag outputs nothing
Why is template_tags not displaying content? models.py @register_snippet class RegisterPageText2 (models.Model): title = models.CharField (max_length = 255) text = RichTextField () def __str __ (self): return self.title wtpages_tags.py @ register.inclusion_tag ('form.html', takes_context = True) def texts (context): print (RegisterPageText2.objects.all ()) return { 'texts': RegisterPageText2.objects.all (), 'request': context ['request'], } form.html <div class = "form-order"> <div class = "container"> <h1> Invoice for OzonePRO </h1> <a onclick="closeForm()"> <img src = "/ static_files / images / close-gray.png"> </a> {% for text in texts%} <p> {{text.text}} </p> {% endfor%} </div> </div> {% for text in texts%} <p> {{text.text}} </p> {% endfor%} outputs nothing -
Render fields conditionally with Django-Filters
I'm working on my Django SAAS app in which I want to allow the user to have some custom settings, like disable or enable certain filters. For that I'm using django-user-setttings combined with django-filters and simple forms with boolean fields: class PropertyFilterSetting(forms.Form): filter_by_loans = forms.BooleanField(required=False) filter_by_tenants = forms.BooleanField(required=False) The issue is that when trying to apply those settings, I keep running into serious spaghetti code: views.py class PropertyListView(LoginRequiredMixin, FilterView): template_name = 'app/property_list.html' context_object_name = 'properties' def get_filterset_class(self): print(get_user_setting('filter_by_tenants', request=self.request)) return PropertyFilterWithoutTenant if not get_user_setting('filter_by_tenants', request=self.request)['value'] else PropertyFilter filter.py class PropertyFilter(django_filter.FilterSet): ... class PropertyFilterWithoutTenant(PropertyFilter): ... and I'd have to do the same thing with the rest of the features. Is there any better way to implement this? -
How to integrate AngularJs with Django
I have little/no knowdlege in AngularJs, i want to create a very simple SPA with django as backend and AngularJs as frontend. User will be able to Register, Login & logout all taking place on the same page when a user logs in they will see a message"Welcome (user email)". This is very easy to do in a normal django web app as we don't even need to create the whole authentication system. But i want to learn how to do this with AngularJS as my employer wants me to do. I have read the basics of AngularJs and it looked well explained (it made sense) but how to integrate it with django. I tried searching on the internet but there is nothing out there, the tutorials that are there are more then 7 years old. -
Why is gunicorn displaying so many processes?
I have a simple web app built with Django & running with Gunicorn with Nginx. When I open HTOP, I see there are so many processes & threads spawn -- for a single tutorial app that just displays a login form. See screenshot of HTOP below: Why are there so many of them open for such a simple app? Thanks -
Executing django server as a subpackage
I am attempting to run a Django server as part of a project which, so far, has another package. If only for learning purposes, I'd like to keep it that way for the moment instead of merging both the core and web packages. I have looked at similar questions, but have not found a solution to my specific problem The tree listed below is the result of running the following command in the root project folder: django-admin startproject web . ├── __init__.py ├── core │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── server.py │ └── task_manager │ ├── __init__.py │ ├── __pycache__ │ └── main.py ├── test ├── venv │ ├... │ └── pyvenv.cfg └── web ├── __init__.py ├── __pycache__ │ ... ├── db.sqlite3 ├── manage.py └── web ├── __init__.py ├── __pycache__ ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py As I want the Django server to be able to access the outer package, my understanding is that I have to cd into the base project directory, and run the web server as such: python -m web.manage runserver Since by default the files created by the django-admin createproject contain absolute package references, I changed the "web.XYZ" … -
collectstatic whitenoise can't see my existing file on deployment to heroku
I've been workingon my app making multiple pushes to deploy on heroku and everything was fine but when I added settings for my django app to use cloudinary to store uploaded files in production whitenoise acted up failing to see files that are existent in my project , I have not made any changes to my static files and my previous pushes to heroku were all okay but now once the collectstatic part of the deploy starts whitenoise presents an issue of not seeing my files yet their paths are still okay and nothing has been changed in static files Im not sure if its the cloudinary settings that are causing this settings.py ... INSTALLED_APPS = [ # my apps 'user.apps.UserConfig', 'store.apps.StoreConfig', 'pages.apps.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'cloudinary_storage', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party apps 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'cloudinary', #'djangorave', #providors 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] .... STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'YOUR_CLOUD_NAME', 'API_KEY': 'YOUR_API_KEY', 'API_SECRET': 'YOUR_API_SECRET', } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' project file structure showing file in question exists error on deployment to heroku -
django getting perticular post from models in view.py class
how to get a photo, video, and other objects related to a particular post from PostImage, PostVideo, PostAudio.... class in views.py? It's returning all the photos, videos of PostImage, PostVideo.... models in the models.py to the display template. here are the models.py and views.py what to change in views.py or models.py so that it returns only the particular image, video from PostImage, PostVideo, PostAudio..... classes in models.py models.py from django.urls import reverse from django.template.defaultfilters import slugify from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericRelation from django_resized import ResizedImageField from django.shortcuts import render from django.http import HttpResponseRedirect from comment.models import Comment class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) email = models.EmailField(max_length=254, blank=False) date = models.DateTimeField(auto_now_add=True) editdate = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) title = models.CharField(max_length=150) body = models.TextField() image = ResizedImageField(size=[480, 360], upload_to='blog/images', blank=True) audio = models.FileField(blank=True) video = models.FileField(blank=True) file = models.FileField(blank=True) YoutubeUrl = models.CharField(blank=True, max_length=200) ExternalUrl = models.CharField(blank=True, max_length=200) # comment app comments = GenericRelation(Comment) class Meta: ordering = ['-editdate', '-date'] def get_absolute_url(self): return reverse('post:postdetail', kwargs={'slug': self.slug}) def __str__(self): return f"By {self.author}: {self.title[:25]}" def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug _title = self.title if len(_title) > 45: _title = _title[:45] unique_slug = self.slug … -
Django: Change a DB record of a model extending an existing model by 1-1-relation
I am extending the default User model with a custom Profile model. They have a 1-to-1 relation (OneToOneField). The Profile stores custom settings of its user. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) allow_export = models.BooleanField(default=False) language = models.CharField(max_length=8, default='en') theme = models.CharField(max_length=32, default='light') I created a JS function which calls a Python API. The Python API should change the theme field of the online user (the page can just be reached when the user is logged in.). So this is the API call. Please not that the function request is a simple post/get request. The only important thing I do here is to send a JSON object with {theme: theme}, for instance {theme: 'dark'}. The request works well. from django.contrib.auth.models import User function changeTheme(theme) { let url = 'api/change-theme'; let data = { theme: theme }; let onSuccess = function (data) { console.log(data); } let onServerError = function () { console.log(data); } let onError = function () { console.log(data); } request('POST', url, data, onSuccess, onServerError, onError); } Now the issue: There is the python function api_change_theme. This function should change the theme of the user`s profile. def api_change_theme(request): # Get post data post = json.loads(request.body) # Get theme name theme … -
Search certain value in comments of reddit post
What is the best way to search text in reddit comments? I saw the "body" objects were nested quite deep in the json and it feels already wrong to use this code comment['data']['body']. Additionally, I get an empty array back so it doesn't find anything. Is there any cleaner/efficient way to loop over all the comments? https://www.reddit.com/r/apexlegends/comments/j3qiw4/heirloom_sets_should_include_a_unique_finisher/.json url = "https://www.reddit.com/r/apexlegends/comments/j3qiw4/heirloom_sets_should_include_a_unique_finisher/.json" if 'comments' in url: comments_json = performRequest(url) for comment in comments_json: if "body" in comment['data'].keys(): foundText = searchText(comment['data']['body']) for text in foundText: tickers.append(text) def performRequest(text): url = text request = requests.get(url, headers = {'User-agent': 'your bot 0.1'}) json_response = request.json() return json_response def searchText(text): return re.findall(r'[0-9]€(\w+)', text) -
change context after the response in sent in django
I have a django view and I'm expecting some of the data in the context to change a few times a second. Can I load a new context into the template after the response is sent without sending a new request? Thanks. the view def debug(request): return render(request, 'all/debug.html', context={"x": x, "y": y}) the template <div class="container"> <canvas id="data"></canvas> <div class="graphing"> <select class="graph-select"></select> <canvas id="graph" width="500"></canvas> </div> </div> <script> let y = "{{ y }}"; let x = "{{ x }}" Chart.defaults.global.animation.duration = 0; var ctx = document.getElementById('graph').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: x.split` `.map(n => +n), datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: y.split` `.map(n => +n) }] }, // Configuration options go here options: { responsive: false, } }); </script> What I want is to dynamically change the x and y data without sending a new request -
how to filter chained dependent select box in django inline formset for every new form
I am developing Django web apllication for Electronics departmental store with full F.A.S. I have two mysql databases for it, 1st is 'product_mast' and 2nd is product_tran. i want to create 'Sales invoice' with one to many relationship in one page. for that i have used two related tables in 2nd "Tran" database, (1)sale_mast and (2)sale_tran. i have created inline-formset template with master and tran form, in which master form data goes to 'master' Table and multiple formset forms data goes to 'Tran' table. in these forms I have used 4 drop down select box,(for that data comes from 1st product_mast database) one from 'supplier' table, 2nd from 'Brand' table, 3rd from 'Items' table and 4th from 'Product' table. all are chained dependent. what i want to do, when i select 'supplier', 'brand' should be filter, 'item' should filter depend on 'brand', 'Product' should depend on 'Item', and finally when i select 'Product', product related price and other fields should be filled in Inputbox automatically. now problem is that all this works fine for first form in formset, but when i add new 2nd form and select all this select box, 1st form data get blank and filled with 2nd … -
Django & Django REST Framework - Adding @decorator_from_middleware(MyMiddleware) to API class based view
I'm wondering if there is a simple way to utilise the @decorator_from_middleware from Django decorators with a class based Dango REST Framework view on a per action basis: e.g., something like this: @decorator_from_middleware(DatasetViewsMiddleware) def retrieve(self, request, uuid=None, *args, **kwargs): ... I can't see anything in the Django REST Framework documents that allows this to be achieved. I assume it may have to be applied as some sort of class Mixin? -
pagination in function based view shows all objects
I have function based view and my pagination won't work properly. I see all objects in a single page, which is a problem, but page numbers are displayed correctly, which is a good thing. my views.py looks like this: def myview(request): qs = A.objects.prefetch_related(Prefecth('something', something, something)) paginator = Paginator(qs, 200) page = request.GET.get('page') page_obj = paginator.get_page(page) context = {'something': something, 'page_obj': page_obj} return render(request, 'mytemplate.html', context) Below is mytemplate.html snippet. I literally used this example from django docs <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> I hope someone can shed some light on it. Thanks in advance. -
Issued with uploading large file in Nginx , resulting in 502 bad gateway error
I am using Nginx, gunicorn and django framework for running my web application , here i am facing issue with file upload which will be stored in db ,the max file size i can upload is 1mb which is approximate ( 5000 rows) , but as i upload more than 1 mb it is showing 502 bad gateway error , my nginx confi file is : code : """ server { listen 80; server_name xxx xxx; client_max_body_size 100M; error_log /var/log/nginx/error.log debug; keepalive_timeout 100; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/mainframe;} location /{ include proxy_params; proxy_pass http://unix:/home/ubuntu/mainframe/mainframe.sock; } } """" my Gunicorn Configration: """ [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/mainframe ExecStart=/home/ubuntu/.local/bin/gunicorn --access-logfile - --workers 3 --bin unix:/home/ubuntu/mainframe/mainframe.sock mainframe.wsgi:application [Install] WantedBy=multi-user.target """ any help will be appreciated 2 -
FormView not saving data in Django
I am trying to allow users to save details of a workout for a specific exercise through submitting a form. My ExerciseDetailView displays the form how I'd like it to: class ExerciseDetailView(DetailView): model = Exercise template_name = 'workouts/types.html' def get_context_data(self, **kwargs): context = super(ExerciseDetailView, self).get_context_data(**kwargs) context['form'] = WorkoutModelForm return context But my problem is with saving the inputted data in the database. I have tried making both a FormView and a CreateView but am clearly missing something: class ExerciseFormView(FormView): form_class = WorkoutModelForm success_url = 'workouts:exercise_detail' def form_valid(self, form): form.save() return super(ExerciseFormView, self).form_valid(form) Here is my referenced WorkoutModelForm: class WorkoutModelForm(forms.ModelForm): class Meta: model = Workout fields = ['weight', 'reps'] My template: <form action="{% url 'workouts:workout' exercise.id %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Save</button> </form> Urls: path('exercise/<int:pk>/detail/', ExerciseDetailView.as_view(), name='exercise_detail'), path('exercise/<int:pk>/detail/', ExerciseFormView.as_view(), name='workout'), And for context here is my Workout model which contains a get_absolute_url method: class Workout(models.Model): weight = models.FloatField(default=0) reps = models.PositiveIntegerField(default=0) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) def get_absolute_url(self): return reverse('exercise_detail', args=[str(self.pk)]) I am not receiving any errors, but when I submit the form my url remains the same, as I hoped, however the page just appears blank and the objects are …