Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found (404) Request Method: GET
I keep getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ home/ The current path, home, didn't match any of these. This is my urls.py for the overall project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('hello_world.urls')), ] this is my code for hello_world urls.py from django.urls import path from hello_world import views urlpatterns = [ path('home/', views.hello_world, name='hello_world'), ] this is my code for hello_world views.py from django.shortcuts import render def hello_world(request): return render(request, 'hello_world.html') -
Unable to install django, i get JWT error
When I try to install django (on Google cloud) I get this message: File "/root/lplatform/back/lplatform_api/urls.py", line 3, in <module> from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView ModuleNotFoundError: No module named 'rest_framework_simplejwt' this is my url.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('lplatform_api.urls')) ] and this is my setting.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", 'rest_framework.authentication.BasicAuthentication' , 'rest_framework.authentication.SessionAuthentication', ), } -
Django: non primary-key auto incremented field
is there a possible way to create a non primary-key auto incremented field like a AutoField/BigAutoField that is not prone to failure(duplicated ids, ...) ? -
Django : Difference between django-admin.py and django-admin
Okay here's the catch. When I create a django project with django-admin.py startproject myproject and starts server like python3 manage.py runserver, it all works fine. However, when I create project with django-admin startproject myproject and starts server like python3 manage.py runserver, it gives me tonnes of system check errors like : django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. or django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. -
How to create a elasticbeanstalk database with 'eb create'
I'm trying to create an ElasticBeanstalk environment using the 'eb create' command for the django-python application I'm developing. All the default necessary aws-infastructures are created. (e.g. cloudformation, loadbalancer, targetgroups, ec2-instance and so on). My application uses a postgresql database. I'm using the following DATABASE-definition in my productive-settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], }} Which uses the default environment-variables, provided by default if the elasticbeanstalk-enviroment creates a database. I tried to automate the creation of the database using the ebextensions as described here I tried the following steps to create the database automated when executing 'eb create': I added the following entries to my '01_container.config' in the '.ebextensions' directory, which by the way is definitely used (because I manipulate other values here and they are correctly changed in the elasticbeanstalk-container-configuration) option_settings: aws:rds:dbinstance: DBEngine: postgres DBEngineVersion: 9.6.16 DBUser: 'anyuser' DBPassword: 'anypassword' I also tried to set the same values using the 'Configuration files' and 'JSON document' described approaches here and none of these worked So what I need to do is to execute 'eb create', let it fail with the KeyError: 'RDS_DB_NAME'. Go to the elasticbeanstalk-environment, I just created and … -
How to get AWS static file urls from Javascript?
I'm trying to get the urls to a few static images from my AWS S3 bucket. I have a couple of javascript functions that change the image a user clicks on (clicking on a like button turns it green). I'm having trouble getting those images to work. The farthest I've gotten was getting a 403 error (Forbidden), and I'm not entirely sure why. Right now, I'm defining a few url variables in script tag and calling them in my JS function. Defining variables: <script> var is_bookmark_url = "{% static 'img/is-bookmark.svg' %}"; var bookmark_url = "{% static 'img/bookmark.svg' %}"; var like_button = "{% static 'img/like-button.svg' %}"; var liked_button = "{% static 'img/like-button-liked.svg' %}"; </script> Calling Variables in JS Function: function changeLike(id) { el = document.querySelector('#' + id) source = el.src if (source.substring(source.length - 26) == "/img/like-button-liked.svg" || source.substring(33, 59) == "/img/like-button-liked.svg") { el.src = like_button_url; } else { el.src = liked_button_url; } } (I know my function is the opposite of elegant, but I wasn't sure how else to get the image names from the urls -- but it works at least.) The point where I'm having trouble is I'm getting the error GET https://appname.s3.amazonaws.com/img/bookmark.svg? AWSAccessKeyId=XXXXXXXXXXXX&amp;Signature=XXXXXXXXXXXXX%3D&amp;Expires=1586147111 403 (Forbidden) So it's definitely … -
m2mchanged signal not working properly as expected
Here when adding an item in the cart and then increasing the quantity of that item. Works fine. The cart item increases the cart item total increases and the car total also gets the correct value. But when I a remove an item or decrease the quantity of that item the CartItem model works, but in Cart model the total don't change. It stays the same total when the items were added to the cart. def m2m_save_cart function is now working as expected. Every I item I add or remove or decrease the quantity. This function should save the changes. It runs as the number_of_items do change but the total doesn't cart models.py # Create your models here. class CartItem(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f"{self.quantity} of {self.item.name}" def pre_save_cart_item(sender, instance, *args, **kwargs): instance.item_total = instance.quantity * instance.item.price pre_save.connect(pre_save_cart_item, sender=CartItem) class Cart(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='cart') items = models.ManyToManyField(CartItem) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) purchased = models.BooleanField(default=False) def __str__(self): return f"User: {self.owner}, items in cart {self.number_of_items}" def m2m_save_cart(sender, action, instance, *args, **kwargs): … -
Custom Model Attributes not being passed to template
I have a custom user model and have my settings.AUTH pointing to my custom model, 'Profile'. I am trying to display a page that will pick one of my Profile objects and randomly display them. Then, my user will be able to choose like or dislike. But I'm stuck at simply getting them to display. As I'm just getting a page that shows 'BIO' without the user's bio, nor the users photo. The logic in views.py is getting me to the template, but the info I need isn't showing up. And on top of that, every time I go to this link, the current logged in user is being changed to a different user! So not sure what's going on there either, but I believe something is wrong with my logic. template.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} <div class="tindero"> {% if user %} <div class="container content is-child box column is-4 is-offset-4"> <img src="{{ profile.photo.url }}"> <p style="font-size: 25px">{{profile.username}}</p> <b>Bio:</b> <p>{{profile.description}}</p> </div> {% else %} <p>Wait for more people to join!</p> <p>Help us get more user. Share this link to your friends! <a href="http://localhost:8000/">http://localhost:8000/</a></p> {% endif %} {% endblock %} views.py def mingle(request): try: … -
Django create db view with multiply between cols, take average and group by time
I have a django model as below: class Source(models.Model): date = models.DateTimeField(primary_key=True, auto_now_add=True) curr_1 = models.DecimalField(decimal_places=2) volt_1 = models.DecimalField(decimal_places=2) curr_2 = models.DecimalField(decimal_places=2) volt_2 = models.DecimalField(decimal_places=2) curr_3 = models.DecimalField(decimal_places=2) volt_3 = models.DecimalField(decimal_places=2) class AvgPower(models.Model): ... Now I want to create a db view for above table group by day with cols as below: power_1 = avg(curr_1 * volt_1) power_2 = avg(curr_2 * volt_2) power_3 = avg(curr_3 * volt_3) Can any one tell me how to create view with "group by", multiply and average along time? -
Only the owner of a object can delete?
My project is a blog REST API where users can post an article. I customized the permissions to only the author owner can edit but whatever user can delete one post. views.py class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() def get_permissions(self): if self.action in ['update', 'partial_update', 'delete']: self.permission_classes = [IsOwnerOrReadOnly] return [permission() for permission in self.permission_classes] def get_serializer_class(self): if self.action == 'create': return CreateArticleSerializer return ArticleSerializer model.py class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(db_index=True, unique=True, max_length=255) title = models.CharField(max_length=255) subtitle = models.CharField(blank=True, max_length=400) body = RichTextUploadingField() image = models.ImageField(upload_to='featured_image', blank=True) def __str__(self): return self.title permissions.py class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user -
chromedriver on different platforms
I am working on a Django project with my group from uni. One of my group mates implemented a scraper using a chromedriver.exe (apparently on Windows). I am working on the project from a Ubuntu. When I run the server (python3 manage.py runserver) I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver': 'chromedriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django real time task automation
Let's say I have a model: class Person(models.Model): name = models.CharField(max_length=255) ... And another: class Group (models.Model): name = models.CharField(max_length=255) persons = models.ManyToManyField(Person) start_time = models.TimeField() end_time = models.TimeField() sunday = models.BooleanField() monday = models.BooleanField() ... All days in a week And finally: class Session(models.Model): group = models.ForeignKey(Group, on_delete=models.PROTECT) person = models.ForeignKey(Person, on_delete=models.PROTECT) STATUSES = ( ("P", "Pending"), ("C", "Completed"), ) status = models.CharField(max_length=1, choices=STATUSES, default="P") day = models.CharField(max_length=15, help_text="What day was this seesion? This is the on of days you chose in the Group") start_time = models.TimeField() end_time = models.TimeField() Okay, I know code doesn't make any sense but I would like to change that.l for you. Let's say I have a few Persons. I go on to create a Group with some Persons in that Group and select the days that these group sessions will take take place and when. a) After I create the Group, I want to automatically create seasions for this week for each person in the Group. This is very easily done by overriding the 'on_save()' function and creating Sessions for the this week. But then what do I do after this week is over? I don't want to go back and re-save this … -
Collapsible Materialize doesn't work on django template
I am learning Django and I am trying to use a collapsible from materialize but without success.. My data, everything is ok, when i comment out , it displays my content. Now when I add the collapsible body, nothing collapse Could someone explain why is that? Here is my code: Base.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <title>Welcome to your workspace {% block title %}{% endblock %}</title> </head> <header> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo center">GDSISA</a> <ul class="left hide-on-med-and-down"> <li class="active"><a href="index.html">My workspace</a></li> </ul> </div> </nav> </header> <body class="container" style="width: 100%;"> {% block content %}{% endblock %} </body> </html> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> Index.html {% extends 'base.html' %} {% block content %} <h1 class="text-center mb-3">Welcome to your worspace!</h1> <ul class="collapsible popout" data-collapsible = "accordion"> {% if latest_question_list %} {% for question in latest_question_list %} <li> <div class="collapsible-header"><i class="material-icons">business_center</i>{{ question.question_text }}</div> <div class="collapsible-body"> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'chiefworkspace:vote' question.id %}" class="text-center mb-3" method="post"> {% csrf_token %} <div class="row"> <ul class="collection"> {% for choice in question.choice_set.all … -
How to get .select2 jQuery to work in django?
I am working on a setting up templates for a django app. I need to use select2 jQuery to select multiple options from the dropdown. I am not sure why it's not being loaded in the html file. Here is the code I have done so far. Please help! {% extends 'scraper/base.html' %} {% load static %} {% block staticfiles %} <script src="{% static 'scraper/jquery.min.js' %}"></script> <script src="{% static 'scraper/select2.min.js' %}"></script> <link href="{% static 'scraper/select2.min.css' %}" rel="stylesheet"/> <script> $(document).ready(function() { $(".js-example-basic-single").select2(); }); </script> {% endblock %} {% block title %}Etsy|Aliexpress Scraper{% endblock %} {% block content %} <div class="row" style="margin-top: 2%"> {% if user.is_authenticated %} <div class="col-lg-4 offset-lg-4"> <form action="/" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control-file" type="file"> </div> <select class="js-example-basic-multiple" multiple="multiple"> <option>United States</option>> <option>UK</option> </select> </form> </div> {% else %} <div class="alert alert-light" role="alert"> <strong>Please log in using the link in the upper-right corner of the page. Thanks</strong> </div> {% endif %} </div> {% endblock %} -
How to get limited results per page in django using pagination?
I am following a udemy course where I am making a real estate website using Django. I have come so far and have been fighting with the errors but I am stuck with the pagination error that I am facing right now. I see everything is working fine in the video but when I follow it exactly it does not work. The issue is that when I set a limit on items per page, it does not seem to be working as I see all the results on the same page. Here is my views.py from django.shortcuts import render from django.core.paginator import Paginator from .models import Listing def index(request): listings = Listing.objects.all().order_by('-id') paginator = Paginator(listings, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'listings': listings } return render(request, 'listings/listings.html', context) It's my Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='listings'), path('<int:listings_id>', views.listing, name='listing'), path('search', views.search, name='search') As you can see, I have set maximum 3 listings per page but I am getting all of them on a single page which is not what I want. It would be great if anyone could help. Thanks for your time and efforts. -
How can I redefine my .wav file as HTML file?
I am uploading my .wav audio media from my Django admin page and accidentally specified Pycharm to read my .wav as TEXT files. I want to redefine it as HTML; how can I do it in Pycharm? -
django NoReverseMatch at / TypeError - missing required positional arguments
path('administration/delete-post/', administration_views.delete_upload, name='delete_upload'), path('administration/delete-post/<slug:post_slug>', administration_views.delete_upload, name='delete_upload'), For some reason, when I added delete class, I had to add two url patterns. When I comment out the first path, It gives me an error of Reverse for 'NoReverseMatch at /administration/ delete_upload' with no arguments not found. 1 pattern(s) tried: ['administration/delete\\-post/(?P<post_slug>[-a-zA-Z0-9_]+)$'] I even stated the slugs on html. {% for post in posts %} <a href="{% url 'delete_upload' %}{{ post.slug }}">Delete Upload</a> {% endif %} With two same url patterns, it worked fine somehow, but now I want to add a confirmation page, and it's causing an error again. views.py def delete_upload(request, post_slug): post = get_object_or_404(VideoPost, slug=post_slug) if request.method == "POST": post.delete() context = { "post": post } return render(request, "administration/confirm_delete.html", context) confirm_delete.html {% block content %} <form action="." method="POST">{% csrf_token %} <h1>Are you sure you want to delete</h1> <p>{{post.title}}</p> <a href="../">Cancel</a><input type="submit" value="Confirm"> </form> {% endblock %} error TypeError at /administration/delete-post/ delete_upload() missing 1 required positional argument: 'post_slug' It directs me to confirm_delete page correctly with the slugs on url, but when I click confirm, the slug is gone on the url and it's causing the error it seems. I see the problem, but I can't fix it... please help. Thank … -
Python Django - HTML for REST API JSON data in Async
I am making a Django web app. So far I have used templates for creating HTML in response to a POST request. I use 'context' to pass data to the template and fill the HTML with that data. This does not require any client-side work. Now I added a REST API to the app to be used Async, and I want all data to be processed by the API and return only in JSON format. This creates a problem, I cant use the templates anymore since I can't use 'context' to fill in the data in the HTML, I have to use client-side JS to do the filling but now I am missing the HTML appropriate to the data received. The web app consists - 1 REST API JSON format 2 Public website 3 Android and iOS app What are the ways in Django for generating HTML for an API JSON response in Async architecture? Are there any alternatives for the templates, solutions, frameworks, JS libraries to get this done in less coding? I do not want to return HTML via API to keep things client mobile app/browser independent. I am hesitant of creating a new frontend like React. I … -
What is the efficient way to resize/process image and upload to s3 in django?
I am fairly new to django. I was wondering what would be the best approach to process an image file and upload to s3. I could think of a couple of approaches but not sure which one to pick. They are as follows: 1) Upload raw unprocessed image directly to s3 from client(mobile app), resize/process it (using Celery) and then replace the original file with the processed one. 2) Send raw image to django, process it and then upload to s3. Thank you. -
Error connecting django to a remote mysql database on aws
I have a django project set up and I’m trying to connect the app to a database being hosted on aws. I’m getting an issue when I run python manage.py check, I get this error: django.db.utils.OperationalError: (1049, "Unknown database 'database-1") I’m able to connect database through mysql command: mysql -u admin -p -h http://database-1.endpoint.us-east-2.rds.amazonaws.com I have my settings.py file configured like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'database-1.endpoint.us-east-2.rds.amazonaws.com', 'NAME': 'database-1', 'USER': 'user', 'PASSWORD': 'pass', 'PORT': '3306', } } -
Django custom user registration form when creating new superuser from terminal raises error TypeError: create_superuser() got an unexpected
Making custom user registration and when creating superuser account from terminal getting this kind of error message TypeError: create_superuser() got an unexpected keyword argument 'first_name' models.py: class AccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, nickname, country, password=None): if not email: raise ValueError("Users must have an email address") ... user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user Any solutions? -
Django alter admin save to alter another table field
I am creating a django site that includes a rudimentary inventory system. Which includes the following models class Stock(models.Model): # Fields location = models.ForeignKey(Location) product = models.ForeignKey(Product) quantity = models.IntegerField() class Transfer(models.Model): # Fields location1 = models.ForeignKey(Location, related_name='location1') location2 = models.ForeignKey(Location, related_name='location2') date_transferred = models.DateField(default=timezone.now) class TransferLine(models.Model): # Choice set direction_set = ( ('1TO2', 'From 1 to 2'), ('2TO1', 'From 2 to 1') ) # Fields transfer = models.ForeignKey(Transfer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() transfer_direction = models.CharField(max_length=4, choices=direction_set, default='1TO2') When I create a new transfer I want to be able to automatically deduct and add the product in the TransferLine from the quantities in the Stock model. I have figured out how to override the save_model method in the admin.py file for the TransferAdmin class, but I cannot figure out how to access the Stock model from within the SaleAdmin class. Is this something that can be done in the admin? Will I have to create my own form? I really wanted to do this from admin because inlinetabular is really easy to do within admin compared to within a custom built form. (At least from what I can find.) Any help on this would be … -
AttributeError at /edit-menu/edit/ 'Product' object has no attribute 'is_valid'
I am trying to pull all of the product names from the Product model, display them and their prices on the screen, and then be able to change the product price of any of these items. I have it so it lists them out and has an input field for the price, but get this error when I submit. AttributeError at /edit-menu/edit/ 'Product' object has no attribute 'is_valid' Please help. views.py: def edit_menu(request): queryset = Product.objects.all() context = { "object_list": queryset } if request.method == 'POST': post=Product() if request.POST.get('price'): if post.is_valid(): post.price= request.POST.get('price') post.save() return redirect('mis446/edit-menu.html', context) else: return redirect(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) Models.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() slug = models.SlugField() def __str__(self): return self.name html: <div class = "container"> <form method = "post"> {% csrf_token %} {% for instance in object_list %} {{ instance.name}}: <input type="number" name="price" value = '{{ instance.price }}'/><br> {% endfor %} <button type ="submit">Submit Changes</button> </form> </div> -
Hide edit/add/remove buttons in Django admin table when field in list_display
I want to hide the edit, add, and remove icons from the Django admin tool for a foreign key field. Is it possible to achieve this? If so, how? This is my code so far: @admin.register(Request) class RequestAdmin(admin.ModelAdmin): list_display = ( "name", "contact_method", "neighborhood", "adults", "children", "prescriptions", "volunteer", "status", "due_date", ) list_editable = ("status", "volunteer") def neighborhood(self, obj): if obj.address and obj.address.get("neighborhood", False): neighborhood = obj.address["neighborhood"] if obj.address.get("details", False): return f"{neighborhood} - {obj.address['details']}" return neighborhood It seems the problem is that I have also registered another model Volunteer. @admin.register(Volunteer) class VolunteerAdmin(admin.ModelAdmin): list_display = ("name", "contact_method", "neighborhood", "valid_ID") def neighborhood(self, obj): if obj.address and obj.address.get("neighborhood", False): return obj.address["neighborhood"] However, I need to keep this model too. So, how can I achieve this? -
Django select related with max field value for each result
I have two models. models.py: class Drink(models.Model): account = models.ForeignKey(Account, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=False, blank=False) # some other fields that don't matter now... class DrinkStock(models.Model): ingredient = models.ForeignKey(Ingredient, null=False, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=14, decimal_places=3, null=False, default=0.000) date = models.DateTimeField(auto_now_add=True) Let me explain why I have two models before someone post a different solution. The idea is to have a stock history. And when I show all the drinks, I need to display them only with their last related stock (the one with the latest date). views.py def drinks(request): drinks = Drink.objects.select_related('stock').filter(account__id=request.session['account_id']) But how can I append the related stock of each drink with the lastest date?