Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Directing Output Paths of Altered Files
I am sorry if this is a dumb question, it seems like it would be simple but has been driving me nuts for days. How can I direct the destination of the output file "pdf01.pdf" to my db? PdfFileWriter().write(open("pdf01.pdf", "wb")) I have gotten the file to successfully output however, it output's to my src directory. My models.py is structured like so: class Model(models.Model): char = models.CharField(max_length=50, null=False, blank=False) file = models.FileField(upload_to=upload_location, null=True, blank=True) I have the user enter a value for 'char', and then the value of 'char' is printed on to a file. The process of successfully producing the file is working, however, the the file is outputting to my source directory. My goal is to have the output file 'pdf01.pdf' output to my db and be represented as 'file' so that the admin can read it. Much of the information in the django docs has been focussed on directing the path of objects imported by the user directly, not on files that have been created by m using the user's data. I have been reading mostly from these docs: Models-Fields Models File response objects I have seen it recommend to write to a buffer, not a file, then … -
Django Autocomplete-Light stuck on autocomplete input field
I've read almost all topics here related to autocomplete-light in django, and I'm still stuck on getting autocomplete input field in my form. Let me explain what I am trying to do. I am building contract template page, where user first input employees data, also populate partner company data and some other relevant data, and then goes to the Create Contract page, where they need to fill the form: search Employee and select, search partner company (which the employee will sign contract with), input other relevant data, and Insert contract details into the base. I am stuck on this "search Employee and select", because I can't get autocomplete input field, but only select field with populated data from my base. Here's my code: settings.py INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cargo_contracts', 'django_filters', ] models.py class Contracts(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) partner_company = models.ForeignKey(PartnerCompany, on_delete=models.CASCADE, null=True) contract_type = models.ForeignKey(ContractTypes, on_delete=models.CASCADE, blank=False) car = models.ForeignKey(Cars, on_delete=models.CASCADE, null=True) contract_number = models.IntegerField(default=0, null=True) signing_date = models.DateField(auto_now_add=False, blank=True, null=True) salary = models.IntegerField(default=0, null=True) contract_percentage = models.IntegerField(default=0, null=True) def __str__(self): return str(self.contract_type) class Meta: verbose_name_plural = 'Contracts' class Employee(models.Model): name = models.CharField(max_length=128, unique=False) jmbg_number = models.CharField(max_length=13) address = models.CharField(max_length=PartnerCompany.ADDRESS_NAME_MAX_LENGTH, unique=False) … -
remove default apps in INSTALLED_APPS
I'm new to Django and python in general and i'm trying to set up a RESTful api using Django and Django Rest Framework, so my problem is that i want to get rid of the default installed apps, something like this: INSTALLED_APPS = [ #'django.contrib.admin', #'django.contrib.auth', #'django.contrib.contenttypes', #'django.contrib.sessions', #'django.contrib.messages', #'django.contrib.staticfiles', 'rest_framework', 'myapp', ] since i want a simple api with no UI that provides me with some data. But when i run python manage.py makemigrations i get the followin error: LookupError: No installed app with label 'admin' does this mean these apps are essential? Thanks in advance. -
Django: Correct "url" tag for use in emails? (A complete "http://..." tag.)
I naively used the {% url tag in an email body, only to discover that it didn't include the site-name. What should I do to create a hyperlink, for use in an email body, that does include the proper site-name? Instead of /foo/bar ... which is the string that the tag returns ... I want: h-t-t-p-s://mysite.com/foo/bar (you know what I meant!) ... without having to hard-code the site-name as a literal in the template. -
Search Option inside category
I'm trying to make a feature where a user can click on a category, and then search within that category. My problem is I can't seem to get the category pk in the html. I've fried my brain trying to find a way, but no luck yet. <form class="searchfield" action="{% url 'posts:cat_search' pk= %}" method="get"> <button type="submit" name="button"> <i class="fa fa-search"></i> </button> <input class="searchfield" id="searchbox" name='q' type="text" placeholder="Search"> </form> I need to specify a category pk for the search, but how? I can grab all the category pks, but just not the one for the correct category class PostListView(LoginRequiredMixin, ListView): model = Post def categories(self): return Category.objects.all() def get_queryset(self): return Post.objects.filter(created_date__lte=timezone.now()).order_by('-created_date') class PostCatView(PostListView): template_name = 'posts/post_category.html' def get_queryset(self): result_pk = self.kwargs.get('pk') return Post.objects.filter(label=self.kwargs.get('pk')).order_by('-created_date') class CategorySearchView(PostCatView): def get_queryset(self): result = super(PostCatView, self).get_queryset() query = self.request.GET.get('q') if query: query_list = query.split() result = result.filter( reduce(operator.and_, (Q(title__icontains=q) for q in query_list)) | reduce(operator.and_, (Q(body__icontains=q) for q in query_list)) ) return result -
Annotating djagno queryset not returning annotations using backwards foreign key. Using geodjango
I have a mysterious problem where annotations are not showing up on queryset using backwards foreign key. Using Django 2.2. Models from django.contrib.gis.db import models class Hexgrid_10km2(models.Model): polygon = gismodels.MultiPolygonField(srid=4326) class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reply_date = models.DateTimeField() ability = models.FloatField(default = 0) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, related_name='replies', on_delete=models.CASCADE, null=True, blank=True) Problem I am first filtering the Hexgrid_10km2 to only those containing Replies as so: most_recent = Reply.objects.filter( reply_date=Subquery( (Reply.objects .filter(user=OuterRef('user')) .values('user') .annotate(most_recent=Max('reply_date')) .values('reply_date')[:1] ) ) ) hex_qs = Hexgrid_10km2.objects.filter(replies__in=most_recent) >>> hex_qs <QuerySet [<Hexgrid_10km2: Hexgrid_10km2 object (197028)>, <Hexgrid_10km2: Hexgrid_10km2 object (197028)>]> I check to see that they do contain replies as so: >>> hex_qs.aggregate(Sum('replies__ability')) {'replies__ability__sum': 2.0} Now the mystery... >>> hex_qs.annotate(avg_ability=Avg('replies__ability')) <QuerySet [<Hexgrid_10km2: Hexgrid_10km2 object (197028)>]> Where is the annotation? Does it have something to do with geodjango which I am using to build the models? I am feeling like a fool. Many thanks for your help as am completely stuck. -
Choose only one item related by foreign key inline
I have two basic models, Product and Image with the latter assigned to the Product via Foreign Key: class Image(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=sku_dir) description = models.CharField(max_length=100, default='', blank=True) product = models.ForeignKey(product.Product, on_delete=models.CASCADE, related_name='images') In admin, I am using the Image model inline: class ImageInline(admin.TabularInline): model = image.Image extra = 1 @admin.register(product.Product) class ProductAdmin(admin.ModelAdmin): search_fields = ['sku', 'name'] list_display = ['sku', 'name', 'price'] autocomplete_fields = ['genus'] inlines = [ImageInline,] I would like to add an additional field to Image to control which image is displayed by default - ideally there would be a radio button for each Image displayed inline on the Product admin form and only one of the images could be selected at once. As I am still learning Django, I sense there is an easy way to do this but I don't know the proper terminology specific to Django to search for an answer (similar to how it took me awhile to discover that "inline" was a term used to display one model's form inside another). How can I add a radio button to each Image which only allows one Image to be selected in the inline form? -
Can't display image in Django template using DRF
My uploaded images are not showing when the template is rendered in the browser. I have set up my media url pattern like this: urlpatterns = [ # App routes .... ] if settings.ENV == settings.DEV: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the project settings, I have the media config like this: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here's a section of the index.html template to display the cover_image: <div class="col-md-5" > <img src="{{ post.cover_image.url }}" class="rounded img-fluid"/> </div> When I run server the page displays properly but the cover_image doesn't appear. It only shows this: The interesting thing is that my uploads are successful and appear in the media/images directory of the project and the terminal log shows a 200 http response but not sure why it doesn't display in the browser. I'm using Django Rest Framework and have templates for individual apps. Here are the project settings context processors: 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', ], Am I missing something? -
using get_context_data() method to retrieve a list of dependant objects within DetailView Django
I am creating a simple car dealership application in Django 3 whereby when goes to a detail page of a category it should list all cars that belong in that category , so in my case car objects are dependent objects of their respective category . I have tried to implement this using get_context_data() method and referencing the two respective models within the DetailView here is my code models.py category from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(null=False, blank=False, max_length=20) description = models.TextField(null=False, blank=False, max_length=120) image = models.ImageField(upload_to='images/') def __str__(self): return self.name def get_absolute_url(self): return reverse('category_detail', args=[str(self.id)]) models.py cars from django.db import models from django.urls import reverse from categories.models import Category # Create your models here. class Car(models.Model): image = models.ImageField(upload_to='images/cars/') make = models.CharField(null=False, blank=False, max_length=30) model = models.CharField(null=False, blank=False, max_length=30) year = models.IntegerField(null=False, blank=False) transmission = models.CharField(null=False, blank=False, max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('car_detail', args=[str(self.id)]) views categories from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Category from cars.models import Car # Create your views here. class CategoryList(ListView): model = Category template_name = 'category_list.html' class CategoryDetailView(DetailView): model = Category … -
Django plotly dash-application returning completely blank page when using django bootstrap components
I'm building a web application with Django and Dash and the excellent django_plotly_dash package. Everything is running smoothly, except for when I attempt to include Django bootstrap components. Adding even a single Django bootstrap component results in a totally blank page - even the html-divs from django_plotly_dash dissappear. Also, the external_stylesheets option seems to be totally ignored, even when add_bootstrap_links=True. This produces the expected output: import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc dis = DjangoDash("test_app_dash", add_bootstrap_links=True) dis.layout = html.Div( [ html.H1("THIS WORKS FINE"), ] ) While this produces a totally blank page (without raising any exceptions): import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc dis = DjangoDash("test_app_dash", add_bootstrap_links=True) dis.layout = html.Div( [ html.H1("THIS WORKS FINE"), dbc.Alert("THIS DOES NOT WORK", id="base-alert", color="primary"), ] ) Here are some of the key files for a minimal working example (see screenshot of full project structure): test_app views.py: from django.shortcuts import render from . import test_app_dash def test(request): return render(request, "test_app/test.html") main urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("test_app.urls")), path('admin/', admin.site.urls), path('django_plotly_dash/', include('django_plotly_dash.urls')) ] test_app urls.py: from django.urls import path from . import views as test_views urlpatterns = … -
custom query set priting in django rest framework
class Topic(models.Model): Title = models.CharField(max_length=150) UserId = models.ForeignKey(User,on_delete=models.CASCADE) GenreId = models.ForeignKey(Genre,related_name='genres',on_delete=models.CASCADE) StartTime = models.DateTimeField(auto_now_add=False) Createdtime = models.DateTimeField(auto_now_add=True) IsBlocked = models.BooleanField() CounterLike = models.IntegerField() IsRepoCalulated = models.IntegerField() def __str__(self): return self.Title class TopicXReport(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s: %s' % (self.TopicId, self.UserId) class TopicXLike(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s: %s' % (self.TopicId, self.UserId) class TopicXVote(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) VoteType = models.BooleanField() status = models.BooleanField() IsBlocked = models.BooleanField() Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): if self.VoteType == True: Votetypebool = "for it" else: Votetypebool = "against it" return '%s "status" %s : %s -> %s' % (Votetypebool, self.status, self.UserId, self.TopicId) i wanted to get api as like all topic fields with topicXlike and topicXreport total number of likes and report i am using django rest framework modelsearializer approach but not able to find spacific like how can i get output how i want output format is below { "id": 1, "Title": "is it", "StartTime": "2020-04-04T16:09:37.781958Z", "Createdtime": "2020-04-14T15:31:11.459409Z", "IsBlocked": false, "totallike": 50, #this fields are coming from topicXlike models "totalvotes": 50,#this fields are coming from topicXvotes models "IsRepoCalulated": 0, "UserId": { "id": 2, "username": "shilpa", … -
AttributeError: module 'django.db.models' has no attribute 'RichTextField'
I'm new to wagtail and am following both official and youtube tutorials (yt ones skip instructions to installing libjpeg and zlib but when I tried to, it says Pillow has them included); Running on windows10, Using latest python, latest wagtail, latest django; Stuck on the first spot, still getting the same issue when running makemigrations or migrate or runserver: File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\home\models.py", line 14, in HomePage banner_subtitle = models.RichTextField(features=["bold", "italic"]) AttributeError: module 'django.db.models' has no attribute 'RichTextField' here's my models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): """Homepage model.""" body = RichTextField(blank=True) templates = "templates/home/home_page.html" max_count = 1 banner_title = models.CharField('Body', blank=True) banner_subtitle = models.RichTextField(features=["bold", "italic"]) banner_image = models.ForeignKey(features= "wagtailImages.Image", null=False, blank=False, on_delete=models.SET_NULL, related_name="+" ) banner_cta = models.ForeignKey( "wagtailcore.Page", ) content_panels = Page.content_panels + [ FieldPanel("banner_title"), ] class Meta: verbose_name = "HomePage" verbose_name_plural = "HomePages" And here's full traceback : Traceback (most recent call last): File ".\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File … -
Django: Query relational models in serializer
I have a Project and Memberships model where each project has a list of members. I need to find out if the current logged in user is listed as a member on the project from the project serializer, but I can't seem to get the request correct in my get_i_am_member method. I need to pass the project id from the Project model to the Membership model to filter the data, then check if the user in the filtered memberships model matches the user making the request. Can someone please assist? Here is my code: ###################################################### # Serializer ###################################################### class ProjectSerializer(LightWeightSerializer): id = Field() name = Field() slug = Field() description = Field() created_date = Field() modified_date = Field() owner = MethodField() members = MethodField() is_private = Field() anon_permissions = Field() public_permissions = Field() is_looking_for_people = Field() looking_for_people_note = Field() i_am_member = MethodField() i_am_admin = MethodField() my_permissions = MethodField() def get_members(self, project): members = Membership.objects.filter(project_id=project.id).select_related() return MembershipSerializer(members, many=True, context=self.context).data def get_i_am_member(self, request): members_list = Membership.objects.filter(project_id=request.project.id).select_related('user') for member in members_list: if member.user == request.username: print(member.user) print("True") return True else: print(member.user) print("False") return False ###################################################### # Models ###################################################### class Project(models.Model): name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("name")) slug = models.SlugField(max_length=250, unique=True, null=False, blank=True, verbose_name=_("slug")) … -
Django return redirect() does nothing
I am currently try to redirect from one view to another view. However, nothing happens, the token gets printed and that's it. class SocialLoginInvUserAPIView(APIView): permission_classes = [AllowAny] @staticmethod def post(request): print(request.data["token"]) return redirect("auth_user_login") Here is the login url: url(r'login/$', LoginInvUserAPIView.as_view(), name='auth_user_login'), -
no match for queryset in UpdateView
The queryset in my view dont send back any result, however when Im executing the raw SQL command with DB Browser for example I have the result I want, I dont understnad why my queryset dont send back anything... I got a 404 Not Found - No soldier to list found matching the query the view: class EditUnitsToListUpdateView(UpdateView): model = SoldierToList fields = ('soldier', 'list', 'author') template_name = 'armybuilder_edit_unit_to_list.html' def get_queryset(self): print (self.model.objects.filter(list=54).query) return self.model.objects.filter(list=54) My models: class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) format_points = models.IntegerField() description = models.CharField(max_length=30) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class Soldier(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) points = models.IntegerField() factions = models.ManyToManyField(Faction) def __str__(self): return self.title class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) My urls: path('list/own/<int:list_id>/<int:faction_id>/addunit', AddUnitsToListFormView.as_view(), name='add_unit_to_list'), path('list/own/<int:pk>/<int:faction_id>/editlist/toto', EditUnitsToListUpdateView.as_view(), name='edit_unit_to_list'), The raw sql that work when executed separatly: SELECT "armybuilder_soldiertolist"."id", "armybuilder_soldiertolist"."soldier_id", "armybuilder_soldiertolist"."list_id", "armybuilder_soldiertolist"."author_id" FROM "armybuilder_soldiertolist" WHERE "armybuilder_soldiertolist"."list_id" = 54 Thanks for your help guys and have a great day ! -
Display Progressbar In Django View When downloading video (youtube-dl)
I am calling 'search/' when button is clicked through ajax call. Now my question is i want to show these details {"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} in a progress bar while downloading in a web page. How should i get the json response from video_progress_hook each time it is call by 'progress_hook' parameter in javascript? Please help. def search(request): file_name=""+str(uuid.uuid1()).split('-')[0]+".mp3" query=request.GET.get("query") ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'}], 'outtmpl': 'media/'+file_name, 'progress_hooks':[video_progress_hook], 'quiet': False, } ydl = youtube_dl.YoutubeDL(ydl_opts) ydl.download([query]) args={'url_link':file_name} return JsonResponse(args) def video_progress_hook(d): args={} if d['status'] == 'downloading': args={"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} return JsonResponse(args) -
Google Cloud Storage URL expires after a day
I switched to google cloud recently for my django app, all works well except that the url to some of my pictures coming from google cloud storage keeps getting expired after a day, and this is really terrible as there is always broken images on my app. I have even set my bucket to public, and still the urls expires after a day. How can one change this? -
how to serve files from /tmp directory in django
I want to serve downloadable files located in the /tmp directory via django. However I don't want these files copied or moved to the static_dir. The whole point of having the files in /tmp is that a cronjob will delete them every night. I realized I could just set /tmp as my static_dir in the django settings, but I already have a static_dir set that I am using in my project. My question is what is the easiest way to allow an end user to download files located in the /tmp directory? If I hit this url: http://localhost:8000/api/v2/tmp/testfile.zip I would expect to download /tmp/testfile.zip Can this be done via just a single entry in urls.py? Or am I going to have to create a new view? -
Add class to model form label Django
I've done a lot of digging on how to accomplish this, and aside from using 3'rd party modules is there not a simple way to customize labels for auto-generated forms in Django? i.e. models.py from django.db import models class Foo(models.Model): email = models.CharField(max_length=200) forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo index.html <form action={% url 'FooApp:results' %} method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> views.py from .forms import FooForm def index(request): form = FooForm() return render(request, 'foos/index.html', {'form': form}) This seems to be the most "Django" way of doing things, but it offers little flexibility in terms of using frameworks such as bootstrap (which requires classes to be added to specific elements including input labels) I have read many answers that use widget customization, for example if I wanted to add the class bar to my email field on my FooForm: forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo widgets = { 'email': TextInput(attrs={ 'class': 'bar' }), } however, I still can't figure out how to add a bar class to the label that is generated along with this input … -
Converting Naive Datetime object to user selected timezone in Django Template
I have Naive Datetime object stored in my Postgresql DB. I know the timezone used in the django project. Now, I have to convert these time objects into user selected timezone values in the template. Is there any way to make all the naive datetime objects to aware objects in the DB using proper migration? -
does django db_index=True index null value?
for example if i have a field name slug = models.CharField(null=True, db_index=True,max_length=50) and while saving data if left slug empty. will database index this saved null value? -
How to initialise a field in Django models using other fields in the model
I would like to call an API that will return the latitude and longitude from a postcode which is part of my Django Model class Nurse(models.Model): firstName = models.CharField(max_length=100, default="") lastName = models.CharField(max_length=100, default="") postCode = models.CharField(max_length=10, default="") area = models.CharField(max_length=100) phoneNumber = models.CharField(max_length=20) email = models.EmailField(max_length=100, null=True) latitude = models.FloatField(max_length=10, null=True) longitude = models.FloatField(max_length=10, null=True) So when a nurse object is created, I would like to call an api (postcode.io) which means I am able to get a latitude and longitude based on the postcode that saves these values to the data model. I need to have the latitude and longitude because I have use for it in a template where I need to access this information. Thanks! -
is there a function that return current path but in Django class
I need function that return part of url but inside ListView(where"XXXX") About project: its just a shopping list. I have 2 classes in models(ShoppingList and ShoppingItem). ShoppingItem looks like this: name = models.CharField(max_length=50, null=False) count = models.IntegerField(null=False) list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE, related_name='shopping_items')** date_created = models.DateTimeField(auto_now_add=True) My ListView class: class ListDetailUpdateView(ListView): model = ShoppingItem template_name = 'xlist_app/ListDetailUpdateView.html' context_object_name = 'products' queryset = ShoppingItem.objects.filter(list = XXXX) My idea is to cut last part of url (for example when i enter list number 2 i have adress http://127.0.0.1:8000/ListDetails/2) and replace "XXXX" with such a function. In my mind it should look like: queryset = ShoppingItem.objects.filter(list = int(request.path.split('/')[-1]) (if there is a better way to do that i will aprreciate all sugestions) -
Django update number of items on each save or delete
I am new to Django and still learning. I am looking to keep track of how many events I have under a test. My current model looks like class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) num_of_events = models.IntegerField(default=0) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test = models.ForeignKey(Test,on_delete=models.CASCADE) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name def save(self): obj, created = Test.objects.update_or_create(name=self.test) obj.num_of_events += 1 super().save() def delete(self): self.test.num_of_events -= 1 super().delete() I thought I could just override the save() function but it does not update on the admin panel and still shows 0. I am trying to figure out what I am doing wrong. -
Django message variable not available in If.. statement
I am trying to use the Django message system to send the user back to their previous page. I have a Delete Customer FBV that can be accessed from multiple locations and after deleting the customer I want to send the user back to where they were. If I do this it works well and I get the behavior I expected: @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' if request.method == "POST": storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust } return render(request, 'delete_customer.html', context) However, I want to be able to use that returnURL variable both in the If "POST" section and in the context variable to send to the render statement. Why when I do this does it not work? @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True if request.method == "POST": del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust, 'returnURL': returnURL } return render(request, 'delete_customer.html', context) Why does this not work? When the redirect hits it says there is nothing to redirect to. How can I …