Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display data from Postgresql query into a Pie ChartJs in Django Framework?
I am working in a Django Project and I would like to show some data from PostgreSql to a Pie ChartJs, but I do not find a way, here my view: from django.shortcuts import render from appclientes.models import Cliente, Municipio from django.db.models import Count Create your views here. def pie_chart_view(request): results = Cliente.objects.values('municipio__nombre_municipio').annotate(clientes_adsl=Count('id')) nombres_municipio = [result['municipio__nombre_municipio'] for result in results] totals = [result['clientes_adsl'] for result in results] print(nombres_municipio,totals) print(results) context = { 'results': results } return render(request, "appclientes/pie_chart.html", context)` `` The QuerySet that I obtained with the sentence print(results) is correct and I here you are my Template where I render the pie: {% load static %} {{ title }} <canvas id="pieChart" width="400" height="100"> <script> var ctx = document.getElementById('pieChart').getContext('2d'); var data = { labels: [{% for result in results %}{{ result.nombre_municipio }}{% endfor %}], datasets: [{ data: [{% for result in results %}{{ result.clientes_adsl }}{% endfor %}], backgroundColor: [ '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', ], }] }; var chart = new Chart(ctx, { type: 'pie', data: data, }); </script> ` But wehe I call the URL it does not show anything just a painted red circle with nothing else. When I inspect in the data appear a number 98343255114 … -
Connecting a Docker-ized Django app to local Postgresql database
For deployment purposes, I have set up my Django app in a Docker container. The setup works, and I am able to serve it using Gunicorn and Apache. However, I can't seem to access my Postgresql database anymore. This database is running locally, and I have no problem accessing it when launching my Django app from outside the container. But when I launch my app from inside the Docker container, all I get is this error: django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5433 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Clearly I am not the first one having trouble with this. I have made sure that Postgresql is listening to external adresses, as stated here, so this shouldn't be a problem. I have also tried playing around with my Docker compose configuration file. Using network_mode=host is not compatible with port bindings. Back in network_mode=bridge, I have also tried as accepted here : extra_hosts: - "host.docker.internal:host-gateway" But it does not change anything, nor does replacing 127.0.0.1 with 172.17.0.0 in my Django .env file. I am a bit at a loss here, so any insight would be appreciated. I have to say that I … -
How to define and increment value of a variable in django template?
I want to define a variable in django template and then increament its value by 1. {% with variable=0 %} {% if some_condition == True %} {{ variable++ }} {% endif %} {% endwith %} For defining the variable, I have figured out that I can use with. How can I increment its value? -
Django LoginRequiredMiddleware continuingly requests reload on the login page
I implemented Django's LoginRequiredMiddleware and it seems to work fine basically. My only problem is, when I'm at the login page I get multiple reload requests per second. In the settings I included the login url and the middleware MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "login_required.middleware.LoginRequiredMiddleware", #<- it's here "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django_htmx.middleware.HtmxMiddleware", "django_browser_reload.middleware.BrowserReloadMiddleware", ] LOGIN_URL = "/login" and this is my view function @login_not_required def login_page( request, ) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse: if request.method == "POST": username: str = request.POST.get("username") password: str = request.POST.get("password") user: AbstractBaseUser | None = authenticate( request, username=username, password=password ) if user is not None: login(request, user) return redirect("landingPage", username=username) else: messages.info(request, "Username or password is incorrect!") return render(request, "a[...]/login.html") I can't find a reason why this happens and would prefer it not to happen to reduce traffic for my app. -
Django User model Groups and permissions error abstracteduser
Im busy creating a User model in Django that can Authenticate users for login, im using abstracteduser to create this model put I am constantly getting this error when making the migrations ERRORS: api.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'api.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'api.User.groups' or 'auth.User.groups'. api.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'api.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'api.User.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'api.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'api.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'api.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'api.User.user_permissions'. The code I've implemented for it: class User(AbstractUser): #User first name eg. Piet first_name = models.CharField(max_length= 60, validators=[MinLengthValidator(3)], verbose_name= "First name", null= False, blank= False) # User surname last_name = models.CharField(max_length= 60, validators=[MinLengthValidator(3)], verbose_name= "Surname", null= False, blank= False) #user type user_type = models.ForeignKey(UserPlans, on_delete= models.PROTECT, related_name='userType') #user email user_email = models.EmailField() # total requests made by the user … -
How to add multiple records from POST in Django?
I had a little difficulty making multiple record in Django. I found a solution myself, but I couldn't make it work. Can anyone with knowledge help? form.html <form action="" method="POST"> {% csrf_token %} {% for work_stations in ws %} {% if work_stations.is_active %} <div class="row"> <div class="col"> <input type="text" class="form-control" placeholder="work stations1" aria-label="" name="ws1"> </div> <div class="col"> <input type="text" class="form-control" placeholder="work stations2" aria-label="last ws2" name="reject_ws"> </div> </div> {% endif %} {% endfor %} <input type="submit" > </form>` Models.py from django.db import models class Master_data(models.Model): ws1 = models.CharField(max_length=100, verbose_name=' ', blank=True) ws2= models.CharField(max_length=100, verbose_name=' ', blank=True) views.py from django.shortcuts import render from .models import Master_data def createpost(request): if request.method == 'POST': posts = request.POST.getlist('post_list[]') Master_data.objects.all().values() post_list_data = posts for x in post_list_data: x.save() return render(request, 'main/cretedata.html') else: return render(request, 'main/cretedata.html') -
Django and Javascript: Multiple events fired with same button not working as expected
I have this ongoing issue with an eventlistener. I can't seem to delegate the proper way and I'm at my wits end with this issue. The user clicks on a delete button which will check the hidden delete checkbox that the inlineformeset provides. This click of the delete button also adjusts the value of the TOTALFORMS in the management form. The box checks properly and the management form adjusts properly. However, when the user submits the form the delete checkbox that is checked submits false (unchecked) and the should-be deleted form is still there when I return back to the page. I have asked this question before and listened to the one suggestion. I also have tried countless things by adding options and rearranging code and making looping through the buttons. . . but nothing. Probably everything but the correct thing by now. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <input type="button" class="sun-not-available" value="Not Available Sunday" onclick="sunCheckOne(); sunHideShow()" id="sun-not-available"> <form id="all-add-form" method="POST" action="" enctype="multipart/form-data"> <div class="sun-hide" id="sun-hide-id"> <div class="sunday-all" id="sunday-all-id"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> <div … -
Django-smart-select doesn't work in FilterSet
Let me start by saying that I am truly a beginner in Django. But I have already tried to search for possible solutions on the Internet and I still haven't solved my problem. In fact, in the template that uses the form based on the "Interventions" model django-smart-selects work. While in the template that uses the form based on the "InterventionFilter", the Plants are not filtered by the Company. Here is my code: models.py class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) company_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True) class Plant(models.Model): ID = models.AutoField(primary_key=True) plant_name = models.CharField(max_length=100) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) class Intervention(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) ID_plant = ChainedForeignKey( Plant, chained_field="ID_company", chained_model_field="ID_company", show_all=False, auto_choose=True, sort=True) filters.py import django_filters from django_filters import DateFilter, CharFilter from django.forms import DateInput from .models import Intervention class InterventionFilter(django_filters.FilterSet): date1 = DateFilter(field_name='start_date', lookup_expr='gte', label='From', widget=DateInput(attrs={'type': 'date'})) #GTE date2 = DateFilter(field_name='start_date', lookup_expr='lte', label='To', widget=DateInput(attrs={'type': 'date'})) #LTE descr = CharFilter(field_name='description', lookup_expr='icontains', label='Description') class Meta: model = Intervention exclude = ['start_date', 'description'] #(date1, date2, descr) fields = ['date1', 'date2', 'ID_company', 'ID_plant', 'descr'] html {% extends 'base.html'%} {% load crispy_forms_tags %} {% block content %} <form method="post" action="{% … -
Embed VueJs Frontend into Django Backend
I have a vue Js frontend and a Django backend running on 2 different ports. Currently I want to embed the frontend into the backend and both only output to a single port. I tried embedding the frontend and backend and both only output 1 port on the backend to run, but essentially still run 2 ports. -
Scheduled Notification in Django
I have a model in which there is a date and time field and the user detail. i want to send a notification to that user on the specified date and time. One solution is to use cron jobs that checks for pending tasks after specified time. But the issue is that if I have a notification scheduled for after 1 minute and cron job interval is say one hour, the notification will be sent after 59 minuter of the scheduled time. Moreover if there are no notifications for next 10 days, the cron job will keep on running in the background. -
how can we intigrate paypal payment in html side to not use views.py
My checkout page involves integrating PayPal, and we have added jQuery to incorporate the PayPal receiver email. All of this is applied using jQuery. If the payment is successful, we want to redirect to the 'verify_placeorder' page. I need information on how to achieve this because the code provided on the PayPal official website is incorrect, and we're encountering errors when using it. My checkout page involves integrating PayPal, and we have added jQuery to incorporate the PayPal receiver email. All of this is applied using jQuery. If the payment is successful, we want to redirect to the 'verify_placeorder' page. I need information on how to achieve this because the code provided on the PayPal official website is incorrect, and we're encountering errors when using it -
Sorting django-mptt record by complex string field as number
I'm using django-mptt to build a hierarchical structure. There is a field "task_id", that represents task id, in the following format "task.subtask.subtask", number of subtasks is infinite. To sort tasks, I'm using standard code order_insertion_by = ['task_id'] It works well, but the fields are sorted as string, i.e. 1.10, 1.2, 1.3, etc. How can I make them sort as a number instead, so it will go 1.2, 1.2, 1.10? -
postgresql db in ubuntu
how to install , create postqresql db and connect to the project in ubuntu I cant do this ...................................................................................................................................................................................................... sudo -u postgres psql [sudo] password for narjes: could not change directory to "/home/narjes/Documents/my_city/my_city": Permission denied psql (14.9 (Ubuntu 14.9-0ubuntu0.22.04.1)) Type "help" for help. postgres=# createuser narjes postgres-# createdb dbsh postgres-# psql postgres-# alter user narjes with encrypted password '123456'; ERROR: syntax error at or near "createuser" LINE 1: createuser narjes ^ postgres=# createuser narjes postgres-# -
Problem with uploading images/files in DRF
I have a Post model which has and image field and a file field. I created a model serializer for it to use it to create new Post objects in an APIView. model: class Post(models.Model): TEXT = "TXT" IMAGE = "IMG" VIDEO = "VID" REPOST = "REP" POST_TYPE_CHOICES = [ (TEXT, "Text"), (IMAGE, "Image"), (VIDEO, "Video"), (REPOST, "Repost"), ] user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") body = models.TextField(max_length=4000, null=True, blank=True) image = models.ImageField(null=True, blank=True) video = models.FileField( validators=[ FileExtensionValidator( allowed_extensions=["MOV", "avi", "mp4", "webm", "mkv"] ) ], null=True, blank=True, ) post_type = models.CharField(max_length=3, choices=POST_TYPE_CHOICES, default=TEXT) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) tags = models.ManyToManyField(Tag, related_name="posts", blank=True) serializer: class PostCreateSeriazlier(serializers.ModelSerializer): tags = serializers.CharField(required=False) class Meta: model = Post fields = ("body", "image", "video", "tags") extra_kwargs = { "body": {"required": True}, } view: class PostCreateAPIView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): serializer = PostCreateSeriazlier(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data post = Post.objects.create( user=request.user, body=data["body"], image=data.get("image"), video=data.get("video"), ) post.tags.set(get_tags_list(data.get("tags", ""))) # a function to create a list of Tag objects out of a string post.save() return Response(status=status.HTTP_200_OK) When I upload an image, this error is raised: ValueError: "<Post: None - foo - IMG>" needs to have a value for field "id" before this many-to-many relationship can … -
Forbidden (Referer checking failed - no Referer.): /callback/
I want to get a post request from a third-party that deals with payments and I want to get payment transactions from their site through and endpoint called callback. I want to save the transactions in my database but I am getting the following error.Forbidden (Referer checking failed - no Referer.): /callback/ I have enabled the CSRF_ALLOWED_ORIGIN and also used the csrf_exempt decorator in the view that will handle post request from the callback but I am getting the error. How do I go about this issue? -
How to pass foreign key model instance from django to reactjs using axios
I have the address model which is basically foreign key aggregation to different other models. And user Model that has an address ID. every user has an address. and every address is combination of other parameters. Now, i want to access these address parameters from user object instance. Models.py class AddressType(models.Model): add_type_name = models.CharField(_("Address Type"), max_length=30) add_type_code = models.CharField(_("Address Type Code "), max_length=2) def __str__(self): return self.add_type_name class AddressProvince(models.Model): add_prov_name = models.CharField(_("Province Name"), max_length=20) def __str__(self): return self.add_prov_name class AddressBranch(models.Model): add_branch_name = models.CharField(_("Branch Name"), max_length=100) add_branch_code = models.CharField(_("Branch Code"), max_length=10) def __str__(self): return self.add_branch_name class AddressDepartment(models.Model): add_dept_name = models.CharField(_("Department Name"), max_length=150) add_dept_code = models.CharField(_("Department Code "), max_length=5) add_dept_floor = models.PositiveIntegerField(_("Department Floor"), default=0) def __str__(self): return self.add_dept_name class AddressContact(models.Model): add_cont_name = models.CharField(_("Contact Name"), max_length=200) add_cont_position = models.CharField(_("Contact Position"), max_length=200) def __str__(self): return self.add_cont_name class AddressSection(models.Model): add_sec_name = models.CharField(_("Section Name"), max_length=250) class Meta: verbose_name_plural = "Address Section" def __str__(self): return self.add_sec_name class Address(models.Model): add_type = models.ForeignKey(AddressType, on_delete=models.CASCADE, blank=True, null=True, related_name="address_type") add_prov = models.ForeignKey(AddressProvince, on_delete=models.CASCADE, blank=True, null=True,related_name="address_province") add_branch = models.ForeignKey(AddressBranch, on_delete=models.CASCADE, blank=True, null=True,related_name="address_branch") add_dept = models.ForeignKey(AddressDepartment, on_delete=models.CASCADE,blank=True, null=True, related_name="address_department") add_contact = models.ForeignKey(AddressContact, on_delete=models.CASCADE,blank=True, null=True, related_name="address_contact") add_section = models.ForeignKey(AddressSection, on_delete=models.CASCADE,blank=True, null=True, related_name="address_section") add_is_sys = models.BooleanField(_("Is System User?"), default=False) def __str__(self): return self.add_section.add_sec_name class UserGroup(models.Model): … -
Django ValueError - didn't return an HttpResponse object. It returned None instead
I am new to Django Framework. I just want to save employee data using a form. But I always get this error no matter what I adjust in my code. ValueError at /employees/create_employee/ The view employees.views.create_employee didn't return an HttpResponse object. It returned None instead. Here are my codes: Project folder: models.py - employees from django.db import models from datetime import date # Create your models here. class Employee(models.Model): first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) sex = models.CharField(max_length=20) position = models.CharField(max_length=100) division = models.CharField(max_length=50) created_at = models.DateField(default=date.today) updated_at = models.DateField(default=date.today) employees/forms.py from django import forms from .models import Employee class EmployeeForm(forms.ModelForm): class Meta: model = Employee exclude = ['created_at', 'updated_at'] employees/views.py from django.shortcuts import render, redirect from .forms import EmployeeForm # Create your views here. def create_employee(request): if request.method == 'POST': form = EmployeeForm(request.POST) if form.is_valid(): form.save() return redirect('employee_list') # redirect to list view or another page else: return render(request, 'employee_form.html', {'form':form}) employees/templates/employees/employee_form.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Create Employee</title> </head> <body> <h1>Create Employee</h1> <form method='post'> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> employees/urls.py from django.urls import path from . import views urlpatterns = [ path('create_employee/', views.create_employee, name='create_employee'), ] -
Access request or request.user in celery task
I am trying to access request.user in django celery task function but it is unable to access as the function is not accepting any request instance, so How can I access it? @shared_task def run_everyday(): return 0 I have configured that celery function in settings.py to run every day like CELERY_BEAT_SCHEDULE = { "run_day": { "task": "blog.tasks.run_everyday", "schedule": crontab(hour=10, minute=5), }, } I tried by defining another function to return request as result but another function needs to pass the request already like @shared_task def run_everyday(): user = get_request_user() return 0 def get_request_user(request): return request.user It shows request is not defined so How exactly can I access it? Do I need to created a middleware to get the request.user in celery task view? If yes, will that be efficient? -
Superuser gets created in the database but I can't login in Django Admin
class UserManager(BaseUserManager): # Manager class for users def create_user(self, email, password=None, **extra_fields): # Method for creating user if not email: raise ValueError("User must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): # autoslugfield """Create and return a new superuser.""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # Custom User Model for the system class User(AbstractBaseUser, PermissionsMixin): "Users in the system" uid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone_number = models.CharField(max_length=20) slug = AutoSlugField(unique=True, populate_from="name") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = "email" When I create a django superuser, a user gets created with value 1 in the fields is_superuser, is_active and is_staff. But when I try to login in the django admin with the credentials, this following error occurs saying - "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." (I've attached a screenshot as well). I have tried several approaches but nothing works. Kindly someone help me. Thank you very much. The following link is the screenshot: Can't Login to Django Admin after … -
cookie cutter template docker crash when i run my api which get data from google api or any other third party api?
i have a django api where i used cookiecutter template for rapid development also i used docker to run there apis now the problem is - i have a one api in which i calling a one trirdparty google api for get some data then save it to my database and return api response as a result what some time crash i see the errror is my docker is reload automatic while api is prograsss ? now but should i do for it give me proper solution | * Restarting with watchdog (inotify) | 2023-09-26 06:58:26.032 UTC [50] LOG: unexpected EOF on client connection with an open transaction | Performing system checks... i try to call a third party api and get that data and to database -
Nginx Loadbalancer return 404
this is my nginx conf file upstream django_servers { server serverone.domain.com:80; server servertwo.domain.com:80; } server { server_name server.domain.com; location /apiservice/api/ { proxy_pass http://django_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } when I call the URLs directly from the browser it works fine(https://serverone.domain.com/apiservice/api/). but if I use the load balancer it returns 404. I am using the Django framework location /apiservice/api/ { include proxy_params; proxy_pass http://unix:/root/backend/app.sock; proxy_pass_request_headers on; proxy_connect_timeout 75s; proxy_read_timeout 300s; } this is the service nginx conf -
I want to add a DRF API route only for testing (override_settings), getting 404
I want the following test to pass, but I am always getting a 404 Error. But I would expect the "get all" request to return all users. import json from django.test.utils import override_settings from django.urls import path, include from rest_framework import routers from frontend.tests.mocks import views from django.test import TestCase app_name = 'frontend' router = routers.SimpleRouter() router.register('api/', views.UserModelViewSet) urlpatterns = [ path('', include(router.urls)), ] @override_settings(ROOT_URLCONF=__name__) class TestJsonSchemaSerializer(TestCase): # APITest doesn't work either def test_custom_serializer(self): resp = self.client.get('/frontend/api/') self.assertEquals(resp.status_code, 200) print(resp.status_code, json.dumps(resp.json())) -
static files not found error in nginix after a correct path mentiond
server { listen 443 ssl; # Listen on port 443 for HTTPS traffic server_name 54.198.4.208; # Replace with your actual domain name or IP address # SSL/TLS Certificate Configuration ssl_certificate /etc/nginx/selfsigned.crt; # Path to self-signed SSL certificate ssl_certificate_key /etc/nginx/selfsigned.key; # Path to self-signed SSL certificate key # Location Blocks for Handling Requests location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/logins/staticfiles/; # Path to the root directory of your Django project } location / { proxy_pass https://54.198.4.208:8000; # Replace with your Django app's IP and port proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } this is my nginix configuration and when i tried http://54.198.4.208:8000/static/style.css this url i got file not found 404 error all my static files are present at the correct directory even i tried to open a static file manually by this path and i got staitc files at right path also i checked with permissions also everything is fine but still its not working i tried manually to see wether the path has static files or but it has all static files at correct loaction -
Trying to add data using postman, when having nested serializer
i have two models students and marks, i've list of students i need to add marks using postman in a nested serializer class. How can i select already existing student? Models.py class Student(models.Model): name = models.CharField(max_length=50, null=False, blank=False) roll_no = models.CharField(max_length=5, null=False, blank=False) mobile_no = PhoneNumberField(null=False, blank=False, unique=True) mail_id = models.EmailField(null=False, blank=False) def __str__(self): return self.name class Marks(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) maths = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) science = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) social = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) def __str__(self): return str(self.student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' class MarksSerializer(serializers.ModelSerializer): student = StudentSerializer() class Meta: model = Marks fields = '__all__' if i give dictionary i'm creating new student, i dont want to create on i want to select existing student, How can i do that? how to send data through postman, when you have a nested serializer class? -
Reverse for 'new_entry' with arguments '(")' not found. 1 pattern tried: ['new_entry'/int:topic_id>/']
I am receiving this error when i run my program. The error is said to occur in my topic.html but i am unsure what I typed in wrong for topic_id to return with an empty string. views.py from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm Create your views here. def index(request): """The home page for Test log""" return render(request, 'test_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'test_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'test_logs/topic.html', context) def new_topic(request): """Add new topic""" if request.method != 'POST': \#No data submitted; create a blank form. form = TopicForm() else: \# POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): form.save() return redirect('test_logs:topics') context = {'form': form} return render(request, 'test_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_vaild(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return …