Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to setup https and enable ssl on Apache mod_wsgi django server
I want to setup https and enable ssl for my django application which runs on a apache mod_wsgi server. I have my ssl certificates in my project directory. Here is the command which I use for starting the server(only mentioned ssl and https parameters):- ./manage.py runmodwsgi --https-only --https-port 8443 --ssl-port 8443 --ssl-certificate-chain-file /apps/django_app/keystore/ROOT-CA.pem --ssl-ca-certificate-file /apps/django_app/keystore/Intermediate-CA.pem --ssl-certificate-key-file /apps/django_app/keystore/server_name.keystore --ssl-certificate-file /apps/django_app/keystore/server_name.crt Here is the output which I get on executing the above command:- Successfully ran command. Server URL : http://0.0.0.0:8000/ Server URL (HTTPS) : https://0.0.0.0:8443/ Server Root : /tmp/mod_wsgi-0.0.0.0:8000:40000 Server Conf : /tmp/mod_wsgi-0.0.0.0:8000:40000/httpd.conf Though the http one runs fine on port 8000, but the https one fails and does not run on port 8443. Please let me know where I may be going wrong. -
how Add Links to a Bootstrap Navigation Bar in django?
i tried to Add Links to a Bootstrap Navigation Bar for login page of Django that finally save in Django administration here is my base.html file <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> {%block head %} <title>Base</title> {% endblock %} </head> <body> <br> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Social Network</a> </div> <div id="navbar" class="navbar-collapse collapse"> {%if user.is_authenticated %} <ul class="nav navbar-nav "> <li><a href="/account">Home</a></li> <li><a href="/account/login">login</a></li> <li><a href="/account/profile">profile</a></li> <li><a href="/account/profile/edit">edit profile</a></li> <li><a href="/account/logout">logout</a></li> </ul> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="/account/login">login</a></li> <li><a href="/account/register">Register</a></li> </ul> {% endif %} </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> {% block body%} <h1>Base</h1> {% endblock %} </body> </html> before it worked not very sort but it worked i checked another questions but i couldnt find my solution -
Django admin with multi-tenancy support, roles and action logs?
I'm looking to find an alternate solution to the built-in Django admin. We have a few main requirements with this admin panel. I understand that no admin panel would come with all solutions out-of-the-box, my goal is to find the one that gives the biggest jump start and takes the least effort to customize upon. I'm looking into multiple admin panels for Django, but most of them are UI refinements or with some extra features. I would like to kindly ask here if anyone know of the admin panel that closely fit what we need that I might have missed. A few main requirements: We use django_tenants for multi-tenancy, but we want the super admin to be able to access an individual tenant. For example, each tenant is our client, and our client want us to update some information for them. We would use the admin panel to update the data inside their tenant on their behalf Roles. We want to have multiple admins and not everyone would be super admin. One person might only be able to access information but not edit any, while another might be able to edit a few selected tables, etc. Action logs. When an … -
memoryview' object has no attribute 'decode' in django postgres
memoryview' object has no attribute 'decode' I am geeting this error while decoding the data from db which is of binary field inst=Instance.objects.all().filter(product=product,site=site) logger.info(inst) instance_file_data={} for ins in inst: instance_i.append(ins.Instance) logger.info(instance_i) strdat=FD.file_data.DECODE('ascii') -
Incremental totals in Django Model
I have a table as below: Example Table and I have a model as class Hours(models.Model): name = model.Charfield(max_length =200) hours = DecimalField(max_digits = 6, decimal_places=2) def total_hours(self): queryset = Hours.objects.aggregate(total_hours=models.Sum('hours')) return queryset['total_hours'] now when I run the code I get all records have the to 37 instead of them having a running total. where did I miss a step? -
Best practice of database design in django rest project?
I have a project where users has multiple permissions based on role assigned. Admin can assign rights(for e.g. can_view, can_approve) in some menu to some role and so on. In this way there can be so many bool flags and some of the flags will be unnecessary for some menu. If I go in like Django Group and permissions model base then there can be so many permissions. For example : ( can create menua , can update menub...) OR any other way which will be appropriate ? class User(): id name role_id(fk) class DashboardMenu(): id name codename(unique) url parent_id class Role(): id name(unique) desc menus(menu_ids (many to many)) class RoleMenuRight(): id role_id(fk) menu_id(fk) can_create can_delete can_update can_view can_approve can_reject #other bool flags Another approach class User(): id name role_id(fk) class Permission(): id name codename(unique) class Role(): id name(unique) desc permissions(permission_ids (many to many)) -
Django: Calculating the amount of the goods
You need to automatically calculate the order amount, redefined the save function, but swears at the lack of id. needs to have a value for field "id" before this many-to-many relationship can be used. class Pizza(models.Model): title = models.CharField(verbose_name='Название пиццы', max_length=100) technology_card = models.ForeignKey(Technology_card, on_delete=models.CASCADE) time_production = models.PositiveIntegerField(verbose_name='Время изготовления', default=10) time_baking_time = models.PositiveIntegerField(verbose_name='Время выпекания', default=10) price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=2, default = 0) def __str__(self): return self.title class Meta(): verbose_name = 'Пицца' verbose_name_plural = 'Пицца' class OrderPizza(models.Model): STATUS_ACCEPT = 'Принят' STATUS_COOK = 'Готовится' STATUS_PREPARED = 'Приготовлен' STATUS_DELIVERED = 'Доставляется' STATUS_EXECUTE = 'Исполнен' STATUS_CHOISES = ( (STATUS_ACCEPT, 'Принят'), (STATUS_COOK, 'Готовится'), (STATUS_PREPARED, 'Приготовлен'), (STATUS_DELIVERED, 'Доставляется'), (STATUS_EXECUTE, 'Исполнен') ) id = models.AutoField(primary_key=True) date = models.DateField(verbose_name='Дата заказа', null=False, default = timezone.now()) name = models.CharField(verbose_name='Имя заказчика', max_length=50) surname = models.CharField(verbose_name='Фамилия заказчика', max_length=50) phone_number = models.CharField(verbose_name='Номер телефона', max_length=10) adress = models.CharField(verbose_name='Адрес доставки', max_length=40) order = models.ManyToManyField(Pizza) courier = models.ForeignKey(Courier, on_delete=models.CASCADE) status = models.CharField( verbose_name='Статус', max_length=12, choices=STATUS_CHOISES, default=STATUS_ACCEPT ) price = models.DecimalField(verbose_name='Стоимость заказа', default=0, max_digits = 10, decimal_places=2) def save(self, *args, **kwargs): self.price = sum([order.price for order in self.order.all()]) super(OrderPizza, self).save(*args, **kwargs) def __str__(self): return ('Заказ от {0} {1}').format(self.surname, self.date) class Meta(): verbose_name = 'Заказ пиццы' verbose_name_plural = 'Заказы пиццы' -
Why isn't my CSS, Javascipt, and bootstrap not showing up in my django site?
I'm using the Djanog for beginners book, it tells me to just copy and paste but when I do so, it doesn't work. The functionalities work(login, logout, etc) it's just the book shows the website being updated and looking way better than mine. Here's my base.html file: <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/\ bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81i\ uXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>{% block title %}Newspaper App{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign up</a> </form> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock content %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4\ YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ 1.14.3/ umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbB\ JiSnjAK/ l8WvCWPIPm49" … -
approve or reject users through django-admin panel once the user signed up
as a newbie, I don't know to do this. I created one user model for users. after the user signed up it should goes up for admin approval. In the admin panel how to make two buttons approve or reject. Once the admin clicked approve button then only the user should be login to the site. if admin reject user won't be login. I need some help. models.py class Vendor(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) id = models.AutoField(primary_key=True, editable=False) vendorid= models.CharField(max_length=100, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.vendorid: # if vendorid of the instance is blank self.vendorid = "VEN_ID" + str(self.id) # generating the vendorid and allocating the value self.save() # saving the instance def __str__(self): return self.vendorid -
How to build a search bar similar to Carvana
We are working on a class project in which we are building a car catalog for first-time car buyers(we are beginners at web dev). We are using Django for the backend and PostgreSQL for the database and vue.js for the front end. We are trying to make a filter bar similar to Caravana's search bar and wanted to know what type of component we could use in vuetify to get a similar look. We decided on dropdowns similar to the website and but ours would have only four options: Price (range slider) Make & Model (similar to carvana) Body style (buttons) door (range slider w/step) seats (range slider w/step) drive (buttons) Features Safety (range slider w/steps) Fuel (buttons) MPG City (range slider) Highway (range slider) Horsepower (range slider) Cylinder (buttons) Engine size (buttons) Engine loc (buttons) For example the the Body dropdown would have 4 subcomponents and each have a filter setting and so on. I guess the part we were confused on was how to get the sub-components with their different buttons under a dropdown like the features dropdown on the carvana website. Links to any blogs and tutorials or any advice for first time web developers would be … -
Create parent and child model in one form django
I am trying to build a form to create a recipe with a Recipe and RecipeIngredient model but when a user is creating a recipe how do I have them both in the same form since RecipeIngredient is dependent on the the foreign key of Recipe which is not yet initialized? Do I need to create a blank recipe everytime a user visits a create page to make this possible? models.py: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) -
How to create a field that contain many values from other model in django
I start learning about django. I'm creating a quiz app in python django. In profile model I want to create two fields that is answered questions and incorrect questions. And these field must be contain many values from Question model. I try ManyToManyField but It doesn't give me correctly result. I'm using sqlite3. What is I can use to resolve this case? Thank you very much. Profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='earth.png', upload_to='profile_images') bio = models.TextField() score = models.IntegerField(default=0,validators=[MinValueValidator(0)]) answered_ques = models.ManyToManyField('QuesModel', blank=True, related_name='Answered_Questions') Incorrect_ques = models.ManyToManyField('QuesModel', blank=True, related_name='Incorrect_Question') Question Model: class QuesModel(models.Model): question = models.CharField(max_length=500, null=True) op1 = models.CharField(max_length=500,null=True) op2 = models.CharField(max_length=500,null=True) op3 = models.CharField(max_length=500,null=True) op4 = models.CharField(max_length=500,null=True) ans = models.CharField(max_length=500,null=True) point = models.IntegerField(default=0, validators=[MaxValueValidator(100),MinValueValidator(0)]) -
Django annotate returning duplicate entries
I'm annotating a queryset like so: class ItemQuerySet(models.QuerySet): def annotate_subitem_stats(self): return self.annotate( count_subitems=Count('subitems'), has_sent_subitems=Case( When(subitems__status=Status.sent, then=Value(True)), default=Value(False) ), ) In this example, SubItem is a model with a foreign key to Item. A strange behaviour happens when I run this code. Suppose we have 1 Item and 2 SubItems linked to it. One subitem has status sent and the other doesn't. When I run annotate on the queryset, the queryset returns the item twice, one with has_sent_subitems set to True and the other set to False. The other strange thing is that, one duplicate has count_subitems == 1, and the other has count_subitems == 1, as if the queryset has split item into two rows, one where status == 'sent' and the other where status != 'sent'. This is basically what the annotated queryset looks like: [ { 'name': 'Item Name', 'count_subitems': 1, 'has_sent_subitem': False }, { 'name': 'Item Name', 'count_subitems': 1, 'has_sent_subitem': True } ] This is what the database looks like, using pseudocode: item = Item() SubItem(item=item, status=draft) SubItem(item=item, status=sent) I'm pretty sure this has to do with line When(subitems__status=Status.sent, then=Value(True)),. Is there any way I can make that line check if only 1 item has status sent, … -
matching query does not exist. Django Error
this is my code for my project, I just get this error I tried to figure it out but I don't get it, Django Error: DoesNotExist at /save_post/ Profile matching query does not exist. views.py, line 75, in save_post form.authore = Profile.objects.get(user=request.user) views.py @login_required def save_post(request): if request.method == "POST": form = Post(content=request.POST['content']) form.authore = Profile.objects.get(user=request.user) form.save() elif request.method == "PUT": data = json.loads(request.body) post_id = int(data["post_id"]) new_content = data["new_content"] post = Post.objects.filter(id=post_id).first() if post.authore.user != request.user: return HttpResponse(status=401) post.content = new_content post.save() return JsonResponse({ "result": True }, status=200) else: return JsonResponse({ "error": "post not found" }, status=400) return index(request) models.py class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Post(models.Model): content = models.TextField() timestamp = models.DateTimeField(default=timezone.now) authore = models.ForeignKey(Profile, on_delete=models.CASCADE) likes = models.PositiveIntegerField(default=0, blank=True, null=True) def serialize(self): return { "id": self.id, "content": self.content, "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"), "authore": self.authore.id, "username": self.authore.user.username, "likes": self.likes.count(), } -
Django DatabaseError Invalid connector for timedelta
Previously, I did implement the ExpressionWrapper to create a custom filter, It's working fine in the postgresql, but when I did run test with sqlite3, then the error said django.db.utils.DatabaseError: Invalid connector for timedelta: *.. class AccessDurationQuerySet(models.QuerySet): def filter_expiration(self, is_expired: bool = False): """ To filter whether AccessDuration already expired or yet. don't use the same `expiration_date` as expression key, because it will clash with `AccessDuration.expiration_date` property. Issue: https://stackoverflow.com/q/69012110/6396981 """ kwargs = {'_expiration_date__gte': Now()} if is_expired: del kwargs['_expiration_date__gte'] kwargs['_expiration_date__lt'] = Now() return self.all().annotate( _expiration_date=models.ExpressionWrapper( models.F('lab_start_date') + (timezone.timedelta(days=1) * models.F('duration')), output_field=models.DateTimeField() ) ).filter(**kwargs) class AccessDurationManager( models.Manager.from_queryset(AccessDurationQuerySet), DefaultManager ): def published(self): return super().published().filter( status=AccessDurationStatusChoices.active ) class AccessDuration(TimeStampedModel): course = models.CharField(max_length=100) duration = models.FloatField(default=settings.DEFAULT_DURATION, help_text=_('In days')) container_duration = models.CharField(max_length=100, default=_('Up 2 hours'), help_text=_('How long a container has to be running, ' 'value based on Docker API Status')) user = models.ForeignKey(User, on_delete=models.CASCADE) lab_start_date = models.DateTimeField(verbose_name=('Start Date'), null=True) status = models.CharField(max_length=20, choices=AccessDurationStatusChoices.choices, default=AccessDurationStatusChoices.inactive) objects = AccessDurationManager() ... Anyway, I'm using docker for my project: docker-compose -f local.yml run django pytest myproject/tests/flows/2_test_invite_student.py::test_invite_student_by_superuser Then the error said: self = <django.db.backends.sqlite3.operations.DatabaseOperations object at 0x7f203c6313a0>, connector = '*', sub_expressions = ['86400000000', '"webssh_accessduration"."duration"'] def combine_duration_expression(self, connector, sub_expressions): if connector not in ['+', '-']: > raise DatabaseError('Invalid connector for timedelta: %s.' … -
How to retrieve user data from djoser endpoint (.../users/me)
How do I retrieve users info from using djoser url /users/me/? I tried to follow the example in this documentation but nothing works out, I keep getting 403 forbidden. I used Bearer, JWT, and Token in the authorization header but none of them worked. https://djoser.readthedocs.io/en/latest/base_endpoints.html -
extending the abstractuser model for two different user types (customer,vendor)
models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): is_customer = models.BooleanField('customer status', default=False) is_vendor = models.BooleanField('vendor status', default=False) class Customer(models.Model): customeruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) username = None email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Vendor(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) username = None email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] … -
How to create regular text in Sphinx and DocString
I added Sphinx auto-documenting to my vanilla Django project. The vanilla Django project has a DocString that I want to keep: """URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ However, Sphinx is trying to process it and gives me these errors: /usr/src/app/porter/urls.py:docstring of porter.urls:5: WARNING: Definition list ends without a blank line; unexpected unindent. /usr/src/app/porter/urls.py:docstring of porter.urls:7: WARNING: Unexpected indentation. /usr/src/app/porter/urls.py:docstring of porter.urls:9: WARNING: Block quote ends without a blank line; unexpected unindent. How can I tell Sphinx to just render the text as-is (just a very long description) and don't process it? -
Has django-coverage a bug in calculation coverage?
I am measuring my test coverage using coverage tool of django. I use coverage html command to see coverage but the result is strange. For example a part of the result is: click to see The question is: How the lines 102 & 104 are not runned? is it possible or it's a bug? Django == 3.2.8 djangorestframework == 3.12.4 coverage == 5.5 -
how to make custom serializer which can handle nested post data for Create API endpoint?
Due to unique business needs, I have to customize the Create API endpoint. Default behavior in django-rest-framework is like this. class Customer(models.Model): fieldA = models.IntegerField(null=True, blank=True) fieldB = models.CharField(max_length=5, blank=True) ... ... class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' class CustomerListCreateAPIView(generics.ListCreateAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer post data { fieldA: 1, fieldB: 'some string' } it sends respond with Created status { id: 1, fieldA: 1, fieldB: 'some string' } However, I want to post data with nested data like this { "customer": { "fieldA": 1, "fieldB": "some string" } } and expected response should be { "customer": { "id": 1, "fieldA": 1, "fieldB": "some string" } } How can I archieve this? -
Django auto increasing PositiveIntegerField per model
In the below django model is it possible to make the position field auto increment per ForeignKey to the ChatGroup model class Channel(Model): chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField(max_length=255, null=True, blank=True) position = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( fields=("chat_group", "position") ) ] Thanks! -
Use all the values in a model to create a chart in Django
I'd like to create a chart with all the information stored in my databse. Specifically I'd like to have in my X axis all the days of the weeks and in the Y axis all the number stored in my database. I've menaged to create sucessufully the labels for the week but when I try to render the data value nothing is showed. Also, if I tried to use data = list(Month.objects.values_list())[2:] to remove the file field and id field my list just return empty. What am I doing wrong? Thank you all MODEL class Week(models.Model): file = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday = models.PositiveIntegerField(null=True) sunday = models.PositiveIntegerField(null=True) VIEW def week_data(request, pk): labels = [f.name for f in Week._meta.get_fields()] data = list(Week.objects.values_list()) context = { 'labels': labels, 'data': data } return render(request, 'data.html', context) HTML <!DOCTYPE html> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="doughnut-chart" width="800" height="450"></canvas> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels: [{% for label in labels %} '{{ label|capfirst }}', {% endfor %}], datasets: [ { label: "Population (millions)", backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", ,"#c45850", ,"#c45850"], data: [{% for value in data %} {{ value }} {% endfor %}] … -
Django create parent model and child model in one form
I am learning Python and Django, and I am trying to create a recipe with a form. The problem is I have two models, Recipe and RecipeIngredient and I don't know how to add recipe ingredients to the form since it requires the primary key of the recipe and from what I understand, the key is not created until after the form is saved? So how can I create a recipe with both the Recipe and RecipeIngredient when Recipe is not yet initialized? Models.py: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # Lasanga description = models.TextField(blank=True, null=True) notes = models.TextField(blank=True, null=True) cookTime = models.CharField(max_length=50, blank=True, null=True) timeStamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) @property def title(self): return self.name def get_absolute_url(self): return reverse("recipes:detail", kwargs={"id": self.id}) # recipes is from url.py app_name def get_hx_url(self): return reverse("recipes:hx-detail", kwargs={"id": self.id}) # recipes is from url.py app_name def get_edit_url(self): return reverse("recipes:update", kwargs={"id": self.id}) def get_image_upload_url(self): return reverse("recipes:recipe-ingredient-image-upload", kwargs={"parent_id": self.id}) def get_delete_url(self): return reverse("recipes:delete", kwargs={"id": self.id}) def get_ingredients_children(self): return self.recipeingredient_set.all() def get_instruction_children(self): return self.recipeinstruction_set.all() class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) quantity = models.CharField(max_length=50, blank=True, null=True) unit … -
django rest framework field validation return value
Where does the return value go for validated fields for serializers with Django rest framework? I looked at the source code, and I thought it was passed to 'attrs' for the main validation method so that I could do manipulation of the field in field_validation for more DRY code. The code below does not work, as the returned value is not passed to attrs, but where does it go? Does it go anywhere? From Sourcecode, it really looks like it does. from anapp.models import CustomObject, CustomUser from anapp.utils import token_hander from rest_framework import serializers class CustomObjectSerializer(serializers.Serializer): uid = serializers.CharField(required=True) token = serializers.CharField(required=True) def validate_uid(self, value) -> CustomObject: uid:str = force_text(urlsafe_base64_decode(value)) myobject: CustomObject = CustomObject.objects.get(id=int(uid)) return myobject def validate(self, attrs:OrderedDict) -> OrderedDict: myobject: CustomObject = attrs.get('uid') user: CustomUser = CustomObject.user if not token_hander.check_token(user, attrs.get('token')): raise serializers.ValidationError({'token': f'invalid token'}) return attrs -
How to see the comments inside Posts in the admin page
Posts class class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) user = ForeignKey(User, on_delete=models.CASCADE ,related_name='UserPosts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" Comment class has inside the post related_name='comments' class Comment(models.Model): text = models.CharField(max_length= 2200) post = models.ForeignKey(Posts, on_delete=models.CASCADE , related_name='comments' ) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to know how can I see Posts comments inside the admin page when going in Posts