Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Conditional model field in admin form (Either link to image or upload image)
I don't know how to do kind of conditional field in model's admin form. I want a model that has multiple images that can be either uploaded or linked from another site. I came up with separate link and upload_file fields and choice field type and then conditionally handle and save it to the database but that approach looks very bad. It makes me to create custom save logic (which i don't know how to do) and it adds extra info into the database. I started to learn django just today, please, add simple solutions not touching django's advanced usage -
How to check current stock remaining
I am struggling to get current remaining stock in my inventory application. I have written code to calculate remaining quantity but it calculates based on purchased quantity only. I want to add total sold quantity and find the difference between purchased and total sold quantity. How do I calculate total sold quantity and calculate the remaining stock. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): sold_quantity = models.IntegerField(null=True, blank=True, default=0) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.product.name @property def get_difference(self): total = self.product.quantity-self.sold_quantity return total Views.py def add_sales(request): form = AddSalesForm() if request.method == 'POST': form = AddSalesForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.product.quantity -= instance.sold_quantity instance.save() return redirect('stock_details') contex = {'form': form} return render(request, 'stockmgmt/add_sales.html', contex) templates {% extends 'stockmgmt/base.html' %} {% block content %} <form method="GET"> <a href="{% url 'add_sales' %}" class="btn btn-primary">Add Sales</a> <p> <table class="table table-bordered"> <tr> <th>Item</th> <th>Category</th> <th>Purchased Qty</th> <th>Sold Qty</th> <th>Remaining Qty</th> <th>Price</th> <th>Action</th> </tr> {% for item in stocks %} <tr> <td>{{item.product.name}}</td> <td>{{item.product.category}}</td> … -
How organize pagination with a large number of pages in Django project?
I have a view.py product_list: ... from django.shortcuts import render, get_object_or_404 from .models import ProductCategory, Product, ProductDetail, ProductSpecialCategory from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger ... def product_list(request, category_slug=None, ): category = None categories = ProductCategory.objects.all() object_list = Product.objects.filter(available=True, is_active=True) if category_slug: category = get_object_or_404(ProductCategory, slug=category_slug) object_list = object_list.filter(category=category) paginator = Paginator(object_list, 1) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) return render(request, 'shop/products/list_by_category/product_list.html', {'category': category, 'categories': categories, 'products': products, }) Based on this handler, I did pagination.html: <nav aria-label="pagination" class="pagination_area"> <ul class="pagination"> {% if page.has_previous %} <li class="page-item next"> <a class="page-link" href="?page={{ page.previous_page_number }}"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a> </li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="page-item focused"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% elif i > page.number|add:'-1' and i < page.number|add:'1' %} {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li class="page-item next"> <a class="page-link" href="?page={{ page.next_page_number }}"> <i class="fa fa-angle-right" aria-hidden="true"></i> </a> </li> {% endif %} </ul> On the interface, I get the **result**: I would like to organize in such a way that: Show … -
Choose certain field in Django import export
I am trying to export some data in Django Admin. And don't know how to make dynamic choices of fields to export, like choices of format file -
How to solve Model matching at /route/blah/ in django
Hello, I am currently making a Django Application that makes use of django allauth and Google Auth Issue is that when I login using django allauth and try to access the route /profile/view/ It throws this huge error at me, below is just the minified version For more help this is the code for the following files ... models.py from django.db import models from django.core.validators import FileExtensionValidator from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): COUNTRY_CHOICES = ( ('No region selected ...', 'No region selected ...'), ('The Caribbean', 'The Caribbean'), ('Central America', 'Central America'), ('North America', 'North America'), ('South America', 'South America'), ('Oceania', 'Oceania'), ('Africa', 'Africa'), ('Europe', 'Europe'), ('Asia', 'Asia'), ) first_name = models.CharField(max_length=30, blank=True, default="John") last_name = models.CharField(max_length=30, blank=True, default="Doe") username = models.CharField(max_length=100, blank=False, null=False, default="FireCDN-User") description = models.TextField(max_length=240, blank=True, default="No informations provided ...") region = models.CharField(max_length=50, blank=False, default="No country selected ...", choices=COUNTRY_CHOICES) avatar = models.ImageField(upload_to='profile/avatars/', default="shared/avatar/default-avatar.png") created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Profiles" class FileUploads(models.Model): FILE_TYPE_CHOICES = ( ('No file type selected ...', 'No file type selected ...'), ('Stylesheets', 'Stylesheets'), ('JavaScript', 'JavaScript'), ('Documents', 'Documents'), ('Images/Pictures', 'Images/Pictures'), ('Scripts', 'Scripts'), ) user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile") file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[ FileExtensionValidator([ … -
How can i read the client Windows Username in a Django intranet web based application?
3 Hello guys, I want to show a message like, hello windows username for the client and get the client windows username.But with win32 functions i get the server windows username, i want the client username, i tried with javascript and it doesn't work, somehow i need to acces his active directory and i don't know how, the site will be intranet and i tried using a LDAP library and somehow it didn't work, am i doing something wrong? Now the site is on a local server, is in develop.I think the domain will be the same because it's intranet, i am not so advance with the domain also and I saw that LDAP use this a lot. I have read about token login and i researched it and still no clue for me. Just give a lead to follow and i will. Thank you guys a lot for the patience.I have found a similar question but is outdated because they asked 7 years ago.And from what i've seen in javascript you can get the user from the user login, but i don t need a login page. And from session i don't think i am able to give the … -
Django form does not save new post using based view function
I have a model as follow: class Post(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) imagefile = models.FileField(null=True, blank=True, upload_to='images', default='default.jpg') There is a bug in the view file that, when I use class base view I can post the new post but whenever I use it as a function it does not save the form. This one works(saves post in database): class PostCreateView(LoginRequiredMixin, AjaxFormMixin, CreateView): model = Post template_name = "app/postform.html" success_url = '/posts' form_class = postform But this one does not(does not save post in database): @login_required def PostCreateView(request): if request.method == 'POST': mform = postform(request.POST or None, request.FILES or None, instance=request.user) if mform.is_valid(): mform.save() # when I print something here, Ill see something messages.success(request, f'Yes!') return redirect('posts') else: mform = postform() return render(request, 'myapplication/postform.html', {'form': mform}) and in postform.html: <form method="POST" action="" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> <!-- {{ form|crispy }} --> </div> </fieldset> </form> and form.py: class postform(forms.ModelForm): class Meta: model = Post fields = ("__all__") exclude = ['date_posted'] -
How i Display form errors with django and ajax
When i console these are my errors: [error] for username: Please fill the username field usersignup:179 [error] for first_name: Please fill the first name field usersignup:179 [error] for last_name: Please fill the last name field usersignup:179 [error] for email: Please fill the email field usersignup:179 [error] for password: Please fill the password field usersignup:179 [error] for password2: Please fill the confirm password field How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. My script: This is my script resukt will be ok when i console but how i display i don't know jquery and ajax. $(document).ready(function () { var $myForm = $('#myform') $myForm.submit(function (event) { event.preventDefault() var $formData = $(this).serialize() var $thisURL = $myForm.attr('data-url') || window.location.href // or set … -
Loading Django static files into css styles
This is the part I am referring to in the question: <div class="my-class" style="background: url({% static 'no_profile_pic/no-profile-pic.png' %}) center / cover no-repeat;"></div> It is finding it: [20/Aug/2020 12:54:30] "GET /static/no_profile_pic/no-profile-pic.png HTTP/1.1" 200 41235 However, it is not loading on my webpage. I have {% load static %} in my html file. Here is my settings file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Any ideas anyone? -
Deploying Django with channels and asgi to heroku
I'm trying to update my Django Heroku server to run asgi as well and consume a WebSocket. I updated the settings, Procfile, asgi file But I can't seem to be able to consume the WebSocket, I get an error: 2020-08-20T12:55:16.708582+00:00 app[web.1]: 2020-08-20 12:55:16,708 INFO "10.11.225.205" - - [18/Jan/1970:07:49:50 +0000] "GET /ws/camera_online/connect/ HTTP/1.1" 404 179 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36" 2020-08-20T12:55:16.708835+00:00 app[web.1]: 2020-08-20 12:55:16,708 DEBUG HTTP response complete for ['10.11.225.205', 15753] 2020-08-20T12:55:16.708954+00:00 app[web.1]: 10.11.225.205:15753 - - [20/Aug/2020:12:55:16] "GET /ws/camera_online/connect/" 404 179 2020-08-20T12:55:16.710071+00:00 heroku[router]: at=info method=GET path="/ws/camera_online/connect/" host=scr-rivendell.herokuapp.com request_id=faa1ffe7-1bbc-4906-a37c-c468a15b4131 fwd="5.102.193.183" dyno=web.1 connect=0ms service=8ms status=404 bytes=326 protocol=https 2020-08-20T12:56:16.356480+00:00 app[web.1]: 10.63.224.151:18254 - - [20/Aug/2020:12:56:16] "WSCONNECTING /ws/camera_online/connect/" - - 2020-08-20T12:56:16.356714+00:00 app[web.1]: 2020-08-20 12:56:16,356 DEBUG Upgraded connection ['10.63.224.151', 18254] to WebSocket 2020-08-20T12:56:16.533805+00:00 app[web.1]: 2020-08-20 12:56:16,533 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. 2020-08-20T12:56:16.533809+00:00 app[web.1]: Traceback (most recent call last): 2020-08-20T12:56:16.533809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/daphne/cli.py", line 30, in asgi 2020-08-20T12:56:16.533810+00:00 app[web.1]: await self.app(scope, receive, send) 2020-08-20T12:56:16.533811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 144, in __call__ 2020-08-20T12:56:16.533812+00:00 app[web.1]: raise ValueError( 2020-08-20T12:56:16.533813+00:00 app[web.1]: ValueError: Django can only handle ASGI/HTTP connections, not websocket. 2020-08-20T12:56:16.534169+00:00 app[web.1]: 2020-08-20 12:56:16,533 INFO failing WebSocket opening handshake ('Internal server error') 2020-08-20T12:56:16.534659+00:00 app[web.1]: 2020-08-20 12:56:16,534 … -
Django First Aplication
After starting python manage.py run server throws such an error, before creating the directory, the server page started correctly. M:\Project_Django\mysite>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x043E18F0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib_init.py", line 37, in import_module import(name) File "M:\Project_Django\mysite\mysite\urls.py", line 17, in from django.urls import path, include,strona ImportError: cannot import name path -
Testing the HomeTests class in tests.py has an error in line 29
I am continuing the Inspections/Defects project that I am doing for fun. On line 29, the error says that HomeTests has no attribute Inspection, and I am trying to find out why. Here is the tests.py file. class HomeTests(TestCase): def setUp(self): Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10,qtyRejected=3) url = reverse('home') self.response = self.client.get(url) def test_home_view_status_code(self): self.assertEquals(self.response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_view_contains_link_to_topics_page(self): inspection_topics_url = reverse(inspection_topics, kwargs={'pk': self.inspection.pk}) -> error occurs at this line self.assertContains(self.response, 'href="{0}"'.format(inspection_topics_url)) I also have been looking in my views.py file to see if it was the source of the problem. I followed the guide at Django URLs Advanced but I had missed something. Here is the views.py file in case you wanted to look at it. from django.shortcuts import render,get_object_or_404 from .models import Inspection # Create your views here. def home(request): inspections = Inspection.objects.all() return render(request, 'home.html', {'inspections': inspections}) def inspection_topics(request, pk): inspection = get_object_or_404(Inspection, pk=pk) return render(request, 'topics.html', {'inspection': inspection}) The views.py has two files, home.html and topics.html. Here they are. {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Final Inspection Report</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> … -
Django inconsistent queries on oracle DB
i'm having really hard times debugging some queries in my project. They look like this: hosts = Hosts.objects.filter(...) query = reduce( operator.or_, ( Q(packages_set__name=name, packages__version__in=versions) for name, versions in some_versions_dict ) ) hosts = dc_hosts.filter(query).annotate( num_packages=Count('packages_set') ).filter( num_packages=len(some_versions_dict) ) and they run really inconsistently, sometimes they finish just fine and sometimes they stay stucked and does not finish. I expect it has something to od with this because I don't really know how to fix that so I just use queries later in a way which does not trigger it (.values_list(...)). Is there some other way how to solve my previous question or is there any way how could I fix it for my db? Thanks for you help this is work related and its driving me crazy currently. -
Ingesting json dump in AWS RDS
I made a django application and want to use an sqlite3 db for local development and a Amazon MySql RDS DB for production. My webserver is running on an EC2 Instance. I have exported the data from the sqlite3 db to a json object using python manage.py dumpdata > datadump.json Is there a way to import this JSON into a MySql DB in RDS or should I tackle this problem in a different manner? Thanks in advance :) -
Python Script integration in a Website (Django)
I have 2 python scripts that I want to implement into a website using Django. They are both based around emails. The first is to check the MX of multiple emails with different variations, and the second is to send out emails to all of the emails provided. How do I implement these scripts below into a Django website? I have a friend who wants to use them, and I want to give him a website rather than have to run it locally. Script #1 from validate_email import validate_email # inputs for verification first_name_input = input(" Enter first name") last_name_input = input(" Enter last name") name = first_name_input + last_name_input domain_input = input(" Enter an email domain(ex. ‘gmail.com’): ") # email variations list email1 = name + "@" + domain_input email2 = first_name_input + "@" + domain_input email3 = first_name_input + last_name_input[0] + "@" + domain_input email4 = first_name_input[0] + last_name_input + "@" + domain_input email5 = first_name_input + "." + last_name_input + "@" + domain_input email6 = first_name_input + "-" + last_name_input + "@" + domain_input email7 = last_name_input + "." + first_name_input + "@" + domain_input email8 = last_name_input + first_name_input + "@" + domain_input email9 = first_name_input … -
django show user information in regroup only to user
Making a web app that lets a user log workouts. I have a page that groups all the logged workouts together by date, using regroup and a for 2 loops. How do I only show the user that is logged in information their own information. When I try to use a 3rd for loop (ex. {% for workout in workouts%}, {% if workout.person == user %})I just get 2 tables with the same information. Heres the code in my template. {% regroup workouts by date_of as dateof %} {%for date_of in dateof %} <table class="table table-striped table-dark mt-3"> <thead> <th scope="col">{{date_of.grouper}}</th> </thead> <thead> <tr> <th scope="col">Body Part</th> <th scope="col">Exercise</th> <th scope="col">Weight(lbs)</th> <th scope="col">Sets</th> <th scope="col">Reps</th> </tr> </thead> <tbody> {% for workout in date_of.list %} <tr> <td>{{workout.body_part}}</td> <td>{{workout.exercise}}</td> <td>{{workout.weight}}</td> <td>{{workout.sets}}</td> <td>{{workout.reps}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} -
Group multiple rows by multiple fields and replace one field with it total sum Django
Let's assume that I have such model in Django represented with below table: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 10 Joe Doe 2020 7 Project_A SomeCity 30 Joe Doe 2020 7 Project_A SomeCity 30 Joe Doe 2020 8 Project_A SomeCity 10 Joe Doe 2020 8 Project_A SomeCity 30 Joe Doe 2020 8 Project_A SomeCity 30 The result which I'm expecting is: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 70 Joe Doe 2020 8 Project_A SomeCity 70 I've tried to achieve this using: Model.objects.values().order_by('Project Name', 'Month').annotate(percentage=Sum('percentage')) Unfortunately result of this operation is slightly different from expected one: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 60 Joe Doe 2020 7 Project_A SomeCity 10 Joe Doe 2020 8 Project_A SomeCity 60 Joe Doe 2020 8 Project_A SomeCity 10 At first look I thought that those records are just different and that's why it's not grouped together, but after looking thoroughly I see group_by should work on those. So, what could be problem here? -
Cannot activate my virtualenv in project folder, I get the error arguments required dest. (windows 10, Powershell)
Going through FreeCodeCamp Django: https://www.youtube.com/watch?v=F5mRW0jo-U4&t I have installed my virtual Environment on Windows 10 using Powershell, but when trying to activate my virtualenv I get the error arguments required dest. Interestingly when I type virtualenv --version, in my project folder it will return the version. However when I type just virtualenv, I receive the error in the title. I am using powershell. Having trouble activating / deactivating.. -
DRF, Djongo and log4mongo
I have setup log4mogo to capture django logs and this is working and putting all the logs into the database correctly. I would like to expose these as part of the drf api and have tried to setup djongo as the orm for this access to the mongo db, but for some reason I get nothing back, I would like to know if someone has any ideas on this. In terms of error, I don't get one I get back an empty dict. So it would seem as the query is coming back with nothing, but there is entries in the db. I am lost as to a direction to go in so any thoughts would be welcome. Model: import djongo.models class Logs(djongo.models.Model): _id = djongo.models.CharField(max_length=400) thread = djongo.models.CharField(max_length=400) level = djongo.models.CharField(max_length=400) timestamp = djongo.models.CharField(max_length=400) threadName = djongo.models.CharField(max_length=400) module = djongo.models.CharField(max_length=400) loggerName = djongo.models.CharField(max_length=400) lineNumber = djongo.models.CharField(max_length=400) message = djongo.models.CharField(max_length=4000) fileName = djongo.models.CharField(max_length=400) method = djongo.models.CharField(max_length=400) View: class UserViewSet(rest_framework.viewsets.ReadOnlyModelViewSet): queryset = logger_api.models.Logs.objects.using('logging_api').all() serializer_class = logger_api.serializers.LogSerializer settings: DATABASES = { 'logging_api': { 'ENGINE': 'djongo', 'NAME': 'logging', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': ********************, 'port': ********************, 'username': ***********, 'password': ***********, 'authSource': *********, 'ssl': True } } } -
django rest framework using action decorator to add path to view financial statement in url
I need the following URLs to work where ticker would stand for a stock ticker such as AAPL or AMZN, and is stands for income_statement. localhost:8000/stocks/ localhost:8000/stocks/<TICKER>/ localhost:8000/stocks/<TICKER>/is/ in the views.py file below I am using a viewset which and router which automatically configures the first two urls above, and for the third url I am using the action decorator with methods=['get'] and url_path="is" to achieve the localhost:8000/stocks/<TICKER>/is/ path. the third URL is configured, but I get a key error for ticker when entering the following url in the browser: localhost:8000/stocks/AAPL/is/ what am I doing wrong here ? models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] class IncomeStatement(models.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="income_statements" ) date = models.DateField(default=datetime.date.today) PERIODICITY_CHOICES = [("ANNUAL", "ANNUAL"), ("QUARTERLY", "QUARTERLY")] periodicity = models.CharField( max_length=10, choices=PERIODICITY_CHOICES, default="annually" ) net_income_continuous_operations = models.DecimalField( max_digits=20, decimal_places=2 views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer # lookup_field = "slug" @action(detail=True, methods=["get"], url_path="is", url_name="is") def get_income_statement(self, request, *args, **kwargs): income_statement = self.queryset.get(ticker=kwargs["ticker"]).select_related( "income_statements" ) … -
Python3.8 Django 3 Method Not Allowed: /delete/DPDC-001 , when I confirm delete, these error appear. Help me, please
[Confirm_delete.html] <form action="{{ object.ref }}" method="post"> {% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Confirm"> </form> [urls.py] urlpatterns = [ path('delete/<pk>', login_required(DeleteView.as_view()), name='s_Delete'), ] [View.py] class DeleteView(DetailView): model = Warehouse template_name = "Slot_Confirm_Delete.html" def get_object(self, queryset=None): obj = super(DeleteView, self).get_object() if not obj.op_user == self.request.user.id: raise Http404 return obj def get_success_url(self): return reverse('success') -
Django Static Files(CSS) don't link with template
Just as the title says, static files somehow are not loading up in my template. I've tried working on it and looking at similar StackOverflow questions but I can't find a solution. I tried debugging it using browser's dev tools. I tried opening the CSS file from there but it just leads me to this error. This leads me to the conclusion that Django doesn't seem to find base.css inside the static folder. I've already done manage.py collectstatic so there shouldn't be a problem. Thanks! Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/static/base.css 'static\base.css' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') template {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'static/base.css' %}"> -
Unable to Fetch particular product for each category
I am always getting all the food items in all Categories. I want to display each Category with each food item. Need to display Category with item belonging to that Category. Please someone help me on this issue to resolve. I have tried looking over internet but couldn't find the solution to it #Models.py class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Menu(models.Model): dish_name = models.CharField(max_length=200, verbose_name='Name of Dish') Desc = models.TextField(verbose_name='Dish Description') Amount = models.IntegerField(null=False, blank=False, verbose_name='Amount of Dish') date_posted = models.DateTimeField(default=timezone.now, verbose_name='Dish Date Posted') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) def __str__(self): return self.dish_name #Views.py def menu(request): products = Menu.objects.all() categories = Category.objects.all() data = {} data['products'] = products data['categories'] = categories template = 'food/menu.html' return render(request, template, data) #html {% for category in categories %} {% if categories %} <div class="col-xs-12 col-sm-6"> <div class="menu-section"> <h2 class="menu-section-title">{{ category.category_name }}</h2> <hr> {% endif %} {% for i in products %} <div class="menu-item"> <div class="menu-item-name">{{ i.dish_name}}</div> <div class="menu-item-price">Rs {{ i.Amount}}</div> <div class="menu-item-description">{{ i.Desc}}</div> </div> {% endfor %} </div> </div> {% endfor %} ` -
How to pass the listview of another model and detailview of another model in same template
i want to pass the listview of post model and detailview of movies model in the same template using class based views class MoviesDetailListView(ListView): model = Movies template_name = 'blog/post_list.html' context_object_name = 'posts' paginate_by = 10 def get_queryset(self): user = get_object_or_404(Movies, name=self.kwargs.get('name')) return Post.objects.filter(name=user).order_by('-date_posted') want to print detailview of model Movies from pk of movies passed in urls i passed the movies name and pk from url but cant get other detail like in detailview we get from pk urls.py urlpatterns = [ path('about/', AboutView.as_view(), name='blog-about'), path('user/<str:username>/', UserPostListView.as_view(), name='user-post'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/<str:name>/<int:id>/', PostCreateView.as_view(), name='post-create'), path('', MoviesListView.as_view(), name='blog-home'), path('<str:name>/<int:pk>/',MoviesDetailListView.as_view(), name='movies-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), -
Can I use edit django cms PlaceholderField before saving (publishing) my page outside of django cms?
I use the placeholder fields outside of the regular django cms. I wish to edit placeholder fields before publishing something. The documentation states: However, any PlaceholderFields in it will only be available for editing from the frontend. And: If you add a PlaceholderField to an existing model, you’ll be able to see the placeholder in the frontend editor only after saving the relevant instance. The only solution I can think of to edit the placeholder is adding a stage of published/unpublished and make unpublished only visible to some with the right access. Or is there a way to "hack" placeholder editing in the admin field? Or some other solution?