Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to increment database row by 1 for every time a link is clicked?
Currently every time I click on a product link on the website the entire database column "views" increases by 1 where as I need it so that just the row increases by 1. The link opens in an external website. The link is opened by clicking on the product image. Any suggestions would be greatly appreciated Models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) Website = models.CharField(max_length=250) Brand = models.CharField(max_length=250) views = models.IntegerField(default=0) views.py def t_detail(request): if request.method == 'POST': T_shirt.objects.update(views=F('views') + 1) if 'q' in request.GET: q = request.GET['q'] owner_obj = T_shirt.objects.filter(Titles__icontains=q) else: owner_obj = T_shirt.objects.all() p = Paginator(owner_obj, 20) page_num = request.GET.get('page', 1) try: page = p.page(page_num) except EmptyPage: page = p.page(1) return render(request, 'tshirtshtml.html', {"owner_obj": page}) html <ul class="products"> {% for v in owner_obj %} <div class="container"> <form method="POST" type="submit"> <button style="border: none;"> {% csrf_token %} <a href="{{ v.Link }}" rel="noopener noreferrer"> <img src="{{ v.Images }}" width="150" height="150"> </a> </button> </form> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }}</b></figcaption> </div> {% endfor %} -
Django perform_update not updating entry
I have a few generic DRF API views: class PageCreateView(generics.CreateAPIView): queryset = Page.objects.all() serializer_class = PageSerializer def perform_create(self, serializer): text = self.request.data.get("text") json = generate_json(text) calculated_level = level_calculate(json) serializer.save(json=json, calculated_level=calculated_level) instance = super().perform_create(serializer) class PageView(generics.RetrieveUpdateDestroyAPIView): queryset = Page.objects.select_related().all() serializer_class = PageSerializer def perform_update(self, serializer): text = self.request.data.get("text") json = generate_json(text) calculated_level = level_calculate(json) serializer.save(json=json, calculated_level=calculated_level) instance = super().perform_update(serializer) The perform_create works perfectly. However the perform_update does not seem to. Should I be doing something differently with the instance or the self object so that it updates the object in question? Generating JSON and calculating the level are both metadata that are dependent on, but which I do not want to include in the POST or PUT request. They need to be re-calculated/re-generated on each save. -
TypeError: 'NoneType' object is not callable in testing django constraints
I want to test this constraint in django who include a condition check birth_date field that must be little than "2011-00-00" but when i run python3 manage.py test i got this error: Traceback (most recent call last): File "C:\Users\dd\Desktop\Dev\django\lemoon\lemoon\account\tests.py", line 45, in test_create_user_under_10 self.assertRaises(IntegrityError,user.save()) File "c:\users\dd\appdata\local\programs\python\python39\lib\unittest\case.py", line 733, in assertRaises return context.handle('assertRaises', args, kwargs) File "c:\users\dd\appdata\local\programs\python\python39\lib\unittest\case.py", line 201, in handle callable_obj(*args, **kwargs) TypeError: 'NoneType' object is not callable models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import UserManager import datetime from django.db.models import Q class User(AbstractBaseUser): email = models.EmailField(max_length=120,unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birth_date = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['birth_date','first_name','last_name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Meta: indexes = [ models.Index(name="email_user_idx",fields=['email']) ] constraints = [ models.CheckConstraint(name="check_birth_date",check=models.Q(birth_date__lte="2011-00-00")) ] tests.py: class Test(TestCase): def test_create_user_under_10(self): User = get_user_model() user = User.objects.test_under_age(email="majid@email.com",first_name="small_majid", last_name="majidi",birth_date="2011-05-22",password="mybestpassword") self.assertRaises(IntegrityError,user.save()) please correct me if i wrote my tests in bad form. -
Django choice not rendering properly using {% if %}
I'm trying to render sort of like a short name for each of the preferred languages in my models.py file, depending on the one the user inputs on the form.py, but it is currently only rendering "EN" across each individual object. How can I fix this? thanks all in advance... Models.py preferred_language_choices = [ ('English', 'English'), ('Español', 'Español'), ('Français', 'Français'), ('Other', 'Other') ] preferred_language = models.CharField(choices=preferred_language_choices, max_length=50, blank=False, null=True) forms.py class GroupForm(ModelForm): class Meta: model = Group exclude = ('admin_approval', 'slug',) page.html {% if group_model.preferred_language == English %} <div class="container"> <p>EN</p> </div> {% elif group_model.preferred_language == Español %} <div class="container"> <p>ES</p> </div> {% elif group_model.preferred_language == Français %} <div class="container"> <p>FR</p> </div> {% endif %} -
How to integrate django, firebase and android for custom authentication?
I am using firebase first time for push notifications. While going through various info I assumed that I may have to use custom authentication to generate unique IDs and send notification to the users using app. Now all processes adding confusion in my mind. My app accepts mobile no and password as login credentials and they are stored in backend our own server configured in django. I am making calls to server apis using retrofit. Now, I want to send a notification after one user completes certain process and it will be informed to another user using notification. I don't know unique firebase device ID of the another user but I know mobile number through backend dB. So how should I send message to server to get another users unique ID and send notification to that user using firebase dynamic dB? Appreciate step by step guidance. Regards, Pd -
Setting up Inlines in Django for a model that has foreign keys to multiple models
I am attempting to set up the admin for a project with inlines that have foreign keys to multiple models. I am using nested-django-admin to set up nested inlines, which is why you will see my admin set up in a slightly different way. user/models.py from django.db import models class Human(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() def __str__(self): return self.name class Parent(Human): job = models.CharField(max_length=50) def __str__(self): return self.name class Child(Human): favorite_toy = models.CharField(max_length=50) def __str__(self): return self.name chore/models.py from django.db import models from user.models import Human, Parent, Child class Chore(models.Model): assigned_by = models.ForeignKey(Parent, on_delete=models.CASCADE) assigned_to = models.ForeignKey(Child, on_delete=models.CASCADE) other_parent = models.ForeignKey(Parent, on_delete=models.CASCADE) description = models.CharField(max_length=50) def __str__(self): return self.description user/admin.py from django.contrib import admin from .models import Human, Parent, Child from chore.admin import ChoreInline import nested_admin class ParentAdmin(nested_admin.NestedModelAdmin): inlines = [ChoreInline] class ChildAdmin(nested_admin.NestedModelAdmin): inlines = [ChoreInline] chore/admin.py from django.contrib import admin from .models import Chore import nested_admin class ChoreInline(nested_admin.NestedStackedInline): model = Chore fk_name = 'assigned_by' class ChoreAdmin(nested_admin.NestedModelAdmin): pass admin.site.register(Chore, ChoreAdmin) I expect this to run smoothly so that the user has the ability to see the chores associated with the child in their admin change and the same for the parents. What I get instead is this error. … -
Django filter traversing multiple foreign keys and generic foreign keys
I've tried a ton of different ways, but I've hit a brick wall with the logic and hoping someone on here may be able to come up with the easily. I have a few different connected relevant models (I've tried to strip out all irrelevant fields and methods for ease of viewing): class InventoryAddress: def __init__(self, warehouse, location, sublocation): self.warehouse = warehouse self.location = location self.sublocation = sublocation # Product Models class ProductMaster(models.Model): internal_id = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Internal ID") class ShoeAttributes(models.Model): style_id = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Style ID") product_master = models.OneToOneField(ProductMaster, related_name='ShoeAttributes', on_delete=models.CASCADE) brand = models.CharField(max_length=30, choices=shoe_brand_choices, default=None, blank=True, null=True, verbose_name="Brand") class Shoe(models.Model): sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="SKU") product_master = models.ForeignKey(ProductMaster, blank=False, null=False, on_delete=models.CASCADE, verbose_name="Brands") size = models.CharField(max_length=20, null=False, blank=False, verbose_name="Size") condition = models.CharField(max_length=25, choices=shoe_condition_choices, blank=False, null=False, verbose_name='Condition') class InventoryItem(models.Model): inventory_sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Inventory SKU") authenticated = models.CharField(max_length=2, choices=yes_no_choices, verbose_name='Authentication Status') # GenericForeignKey for Specific Product content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') def movements(self): movements = InventoryMovement.objects.filter(inventory_item=self) return sorted(movements, key=lambda x: x.datetime_entered, reverse=True) def completed_movements(self): movements = InventoryMovement.objects.filter(inventory_item=self, datetime_completed__isnull=False) return sorted(movements, key=lambda x: x.datetime_completed, reverse=True) def current_location(self): movements = self.completed_movements() if movements: … -
Django & React CORS error - will allow GET requests but not POST
I have created an app using django for the backend and react for the frontend (structured within a django app). Hence there are CORS requests. I have added installed CORS for django and added the following to the settings: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", ] However, when I can make REST requests from react using the prefix "http://localhost:8000", I get the error 403 forbidden. For instance, it will let me login but when logging out I get a 403 forbidden error. I can make GET requests fine and when I tested the API using an external tool like Postman there are no issues. Please advise. -
How to get specific id from for loop in django template?
I'm working with django and javascript, I'm trying to follow and unfollow multiple users without refreshing the page. therefore i'm using ajax. The problem which i'm facing right now is that the first follower is getting follow and unfollow no matter if i click on that user or on other user.. its an obvious behavior because i couldn't understand how to get specific id of user from the for loop so that i can use that user in a js function. {% if follower.user in request.user.userprofile.follower.all %} <span><a class="btn btn-success" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}UnFollow</a></span> {% else %} <span><a class="btn btn-warning" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}Follow</a></span> {% endif %} </div><!--/ followers-body --> {% endfor %} <script> $(document).on('click','a[id^=follow-button]', function (e) { var user = $('#follow-button').attr('toggle'); //this user is coming the first use of looping object..no matter if i click on the 2nd or 3rd user of the loop. console.log(user,'im im im tested'); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "profiles:toggle" %}', data: { user_toggle: user, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'POST', }, success: function (json) { result = json['result'] console.log(result,"maii mai maima maima a") if (result) { document.getElementById("is_following").innerHTML = '<a class="btn btn-success" id="follow-button" toggle="{{user.userprofile}}" type="submit">{% csrf_token %}UnFollow</a>' } else document.getElementById("is_following").innerHTML = '<a class="btn … -
How to get all field of a model for connected with Foreign Key?
I have two model like given in bellow; class tagReferenceLocationInfo (models.Model): tag = models.ForeignKey(tag,on_delete=models.CASCADE) ref = models.ForeignKey(mapReferencePoints, on_delete=models.CASCADE, related_name="refPoint") map = models.ForeignKey(map, on_delete=models.CASCADE, related_name="tag_ref_map") corX = models.IntegerField() corY = models.IntegerField() date = models.DateTimeField(auto_now=True) def __int__(self): return self.tag class mapReferencePoints (models.Model): referenceName = models.CharField(max_length=30) corX = models.IntegerField() corY = models.IntegerField() def __str__(self): return self.referenceName I want to use this queryset result as a json; queryset = tagReferenceLocationInfo.objects.select_related('ref').filter(tag_id__in=id_list, date__gte=startDate, date__lte=queryset) I use; data = serialize("json", queryset) I got only mapReferencePoints ids but ı want to get also "referenceName" field. How can serialize this queryset result to get "referenceName" filed of mapReferencePoints model. -
Why can't I upload a image by Django?
I'm going to make a book bulletin board using the django and put a picture of the book in it and post a post. But the text is going up, but the picture isn't going up. i add MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' in settings.py model.py class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.TextField() author = models.TextField(max_length=50) content = models.TextField() image = models.ImageField(upload_to='image/',blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) like_user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_book') def __str__(self): return self.title form.py class Book_Form(forms.ModelForm): class Meta: model = Book fields = ('title','author', 'content','image') widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'title' } ), 'author': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'author' } ), 'content': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'content', } ), } create.html {% block content %} <form action="" method = 'POST' enctype="multipart/form-data" style= 'margin:40px; height:50px; width:80%;'> {% csrf_token %} {{form.as_p}} </div> <div class = "d-grid gap-2 col-4 mx-auto" style= 'margin:20px; height:50px;'> <input type="submit", class="btn btn-primary" value='제출'> </div> </form> {% endblock content %} view.py @login_required def create(request): if request.method == 'POST': book = Book_Form(request.POST, request.FILES) if book.is_valid(): book = book.save(commit=False) book.user = request.user book.save() return redirect('books:detail', book.pk) else: form = Book_Form() context = { 'form': form, } return render(request,'books/create.html',context) If I try … -
How to serialize parent and child model objects properly?
Here I am trying to return the children serializer data like this but this is not working. How to solve this issue ? model class Type(models.Model): name = models.CharField(max_length=200, unique=True) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, null=True, blank=True) serializer class ListTypeSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Menu fields = ['name', 'children'] # for some reason I can not do `return obj.type_set.values('name')` # since I have so many customized variable names. # I am displaying only name here in question. def get_children(self, obj): return ListTypeSerializer(obj.type_set.all(), many=True, context={'request': self.context['request']}).data Error: raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Type is not JSON serializable -
Django doesn't submit my form if I using individual fields
I need to render my Django form fields individually because of design purposes. It looks good but if I hit submit It doesn't do anything just a short blink. If I render the whole {{ form }} it works well. I don't have any ideas about what am I doing wrong. Could you guys please help me? html <form method = "POST"> <div class="container w-75 bg-light rounded-3 pt-3"> <div class="form-group"> {% csrf_token %} {% comment %} {{ form }} {% endcomment %} <div class="row"> <div class="col-4 border-right border-primary p-3"> <h6 class="text-primary">1. text.</h6> {{ form.att_v001 }}<br> </div> <div class="col-4 border-primary pt-3 pl-4"> <h6 class="text-primary">2.text.</h6> {{ form.att_v002 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">3. text.</h6> {{ form.att_v003 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">4. text.</h6> {{ form.att_v004 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">5. text.</h6> {{ form.att_v005 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">6. text.</h6> {{ form.att_v006 }}<br> </div> </div> <button class="btn btn-large btn-primary" type="submit">Mentés</button> models.py class Attitud(models.Model): def __str__(self): return str(self.user_name) class question(models.IntegerChoices): Nem_jellemző = 0 Néha_jellemző = 1 Nagyon_jellemző = 2 user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) att_v001 = models.IntegerField(default=0, null=True, blank=False, choices=question.choices) att_v002 = models.IntegerField(default=0, null=True, blank=False, choices=question.choices) … -
error in django rest api and react in production
i have built rest api with django and deploy it to server , the problem is when i call the api from react in my local machine it works but when i run npm run build and deploy react and django together , i got alot of errors in api like error connection refused and 403 note that i have disabled all security and installed django-cors-headers and i set origin to allow all . so whats the problem now . thank you in advanced -
Refactoring Django model setup advice
As a learning exercise I am creating a way for generate Student Report Cards. I was able to create the desired outcome in the current version by hardcoding each Standard as its own field in the model but there was a lot of repetition and was hoping to improve it. Sample of current models.py with lots of repetition Sample of current forms.py with lots of repetition Current Front-End How can I re-create the formset above with less code? Here's what I'm trying so far but I've come across some issues I can't find a solution to. Any advice would be appreciated. #models.py class ReportCard(models.Model): PROGRESS_INDICATOR = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('NA', 'NA') ] student_perm_number = models.CharField(max_length=51, default='123456789') reporting_year = models.CharField(max_length=10, default='2020-2021') # Grade Received each Trimester standard = models.ForeignKey('reportforms.Standard', on_delete=models.CASCADE, null=True) t1 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t2 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t3 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) # Math, Language Arts etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False) grade = models.ForeignKey(Grade, on_delete=models.CASCADE, blank=True, null=True) # Shapes, Geometry etc... class Standard(models.Model): domain = models.ForeignKey('reportforms.Domain', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100, blank=False, null=True) The form is pretty simple #forms.py class ReportCardForm(ReportCardForm): class Meta: model = … -
How to restrict Endpoint
I am creating a multi-vendor marketplace with django. I have an endpoint for retrieving, updating and deleting a product that belongs to a store like this: localhost:8000/name-of-store/int:product_id. Note: "name-of-code" is the slug of the store. This is the code below: class EditItemAPIView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ItemSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): item = Item.objects.filter(pk=self.kwargs['pk']) print(item) return item With this code, if I append the id of a product that does not belong to a particular store in the url above i.e I do localhost:8000/name-of-store/5, where 5 is the id of a product that belongs to another store, it gets the product. How do I implement some kind of restriction such that if I try append the id of a product not belonging to the shop whose slug is in the url I get a 401 message? Any help will be greatly appreciated. -
Django | HTMLField not being saved using TinyMCE
I'm using django-tinymce to save HTML data into a field. Nontheless, the HTML content is not being saved meanwhile the rest of the form is. Also, there are no error messages on the console (python and browser). There is a similar issue and another one which take care of this, however, the solution doesn't work for me. models.py from tinymce.models import HTMLField class Thing(models.Model): field = HTMLField(null=True, blank=True) forms.py from tinymce.widgets import TinyMCE class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class ThingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.visible_fields(): form.field.widget.attrs['class'] = 'form-control' def save(self, commit=True): data = {} form = super() try: if form.is_valid(): form.save() else: data['error'] = form.errors except Exception as e: data['error'] = str(e) return data class Meta: model = Thing fields = '__all__' widgets = { 'field': TinyMCEWidget(attrs={'required': False,}) } views.py class ThingCreateView(LoginRequiredMixin, CreateView): [model, form, template, ...] def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'add': form = self.get_form() data = form.save() else: data['error'] = "Error" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context The package IS in … -
how to get values from django views to django template script tag
this is my views.py file def xyz(request): year="Dec 24, 2021 10:40:44" return render(request,"abc.html",{"year":year}) this is my HTML file <script> (function () { let birthday = {{year}}, countDown = new Date(birthday).getTime(), x = setInterval(function() { ..... ..... ..... </script> i am not able to accept the value of year in let birthday variable I actually want to make a countdown timer and the problem is the value which I am sending from my python file is not working -
Creating a favourites list in Django, what would be the best option a new model or an array of dictionaries?
So i am just messing around and trying to practise building django apps and trying improve my coding and basically came to think about apps in scale and ease of use and efficiency etc. I was hoping to get advise / answers from the community about what would be best and why that would work best. I hope this is actually the right place to post such a question, if not please let me know where it would be more appropriately posted? So my question is for agruments sake i create a app where users can share quotes and you can save your favourite quotes, just something super basic. But in terms of creating a new model called "Favourites" with fields of; user - fk , quotes - fk or having an array field on the user model, that stores a dict with key value pairs; { quote : "yabadabadoo", url_of_quote : "www.quote-app.com/flintstones" } what would actually be a better option? In terms of scale, say this is so popular and has millions of users, would creating a new model not slow things down or make it the app less efficient as it would have to look for the data, … -
drf-yasg: Image field not displaying in swagger ui
I am new to django-rest-framework. I am using DRF and drf-yasg Swagger. Can any body help to upload image from request body? I am not able to upload image from request body. My current view.py: @swagger_auto_schema(method='post', request_body=MySerializer) @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass my_serializer.py: class MySerializer(serializers.Serializer): profile_img = serializers.ImageField() profile_img = serializers.ImageField() Can any one explain the problem? -
Connecting to a Postgres database with Django and sqlalchemy
I'm having trouble with connecting to a Postgres database in a Django Python app. It seems to be using the sqlalchemy library and trying to connect to postgresql+pg8000://username:password@46.195.0.100:5432/dbname?ssl=True. The error I get from Django is the following: TypeError: connect() got an unexpected keyword argument 'ssl' When I tried removing the ssl=True from the database URL, I got the following error message: sqlalchemy.exc.InterfaceError: (pg8000.exceptions.InterfaceError) {'S': 'FATAL', 'V': 'FATAL', 'C': '28000', 'M': 'no pg_hba.conf entry for host "51.2.345.678", user "upeducation", database "upeducationnetwork", SSL off', 'F': 'auth.c', 'L': '489', 'R': 'ClientAuthentication'} (Background on this error at: http://sqlalche.me/e/14/rvf5) I'm doubly confused because I have no idea what that host is in the message: 'no pg_hba.conf entry for host "51.2.345.678" Even though it seems like Django is routing through something else while trying this locally, I'm able to connect to the database with and without SSL on my local machine with a SQL client. -
Django: How to put issue check condition
I am working on a Cylinder management system in which I want to put a check condition that if the cylinder is available then only it can be issued and similarly a cylinder can be returned if it is issued. But was unable to write logic, Please help me out to write the logic for this functionality. here is my models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','available'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) issue_Date=models.DateTimeField(null=True) issue_user=models.CharField(max_length=70,null=True) return_Date=models.DateTimeField(null=True) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_Date=self.issueDate) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_user=self.userName) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class ReturnCylinder(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) availability=models.CharField(max_length=20,choices=ava) status=models.CharField(max_length=10,choices=fill) returnDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Issued': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(return_Date=self.returnDate) if self.availability=='YES' or self.availability=='yes': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') else: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') super().save(*args,**kwargs) def __str__(self): return str(self.cylinder) -
Centering text in Django Admin list view
In the Django Admin list view, is there an easy way of centering the boolean icons below their headings? Please see the attached image. Thanks not-centered example -
jquery-3.5.1.js:10099 POST http://localhost:8000/pmu_dash/filter/ 403 (Forbidden)
3.5.1.js:10099 POST http://localhost:8000/home/filter/ 403 (Forbidden)". i am trying to post data via js to view.py // myclick function function myClick(){ var table = document.getElementById("meastable"); var rows = table.getElementsByTagName("tr"); console.log("got here"); for (i = 0; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); var URL="{% url 'home:filter' %}" var data = {'count': id, 'X-csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()}; $.post(URL, data); }; }; currentRow.onclick = createClickHandler(currentRow); } } -
How can I render multiple datasets for charts js in Django?
My view: from django.shortcuts import render from django.apps import apps Item = apps.get_model('inventory', 'Item') Cancellations = apps.get_model('cancellations', 'Cancellations') def chart_display(request): labels = [] data = [] queryset = Item.objects.all() for item in queryset: labels.append(item.item_name) data.append(item.quantity) data = { 'inv_labels': labels, 'inv_data': data, } return render(request, 'pie_chart.html', data) My HTML: <div class="grid-container"> <div class="inv-class"> <h2>Inventory Stats</h2> <canvas id="inventory-chart"></canvas> </div> <div class="item2"> <h2>Cancellation Stats</h2> <canvas id="layanan_subbagian"></canvas> </div> </div> <script> $(function () { var data = { type: 'bar', data: { datasets: [{ data: {{ inv_data|safe }}, backgroundColor: [ '#3c8dbc', '#f56954', '#f39c12', '#ff0000', '#008000', ], label: 'Quantity' }], labels: {{ inv_labels|safe }} }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('inventory-chart').getContext('2d'); window.myPie = new Chart(ctx, data); } }); </script {% endblock content%} My question is what would be the best way to render the data from a different model but on the same page? When I make a second dataset in my chart_display view and try to render it alongside the first, it doesn't render. I tried changing my view to: def chart_display(request): inv_labels = [] inv_data_qs = [] queryset = Item.objects.all() for item in queryset: inv_labels.append(item.item_name) inv_data_qs.append(item.quantity) inv_data = { 'inv_labels': inv_labels, 'inv_data': inv_data_qs, } can_labels …