Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why the name of the form variable is being displayed? django
I have this form form.py from django import forms from .models import User LETTERS= [ ('a', 'a)'), ('b', 'b)'), ('c', 'c)'), ('d', 'd)'), ('e', 'e)'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=LETTERS) and this view views.py from django.shortcuts import render from questoes.models import Questao from .forms import CHOICES # Create your views here. def prova(request): questoes = Questao.objects.order_by('?')[:5] form = CHOICES if request.method=='POST': dados = { 'questoes': questoes, 'form':form(request.POST) } return render(request,'provas/prova.html', dados) else: dados = { 'questoes': questoes, 'form':form } return render(request,'provas/prova.html', dados) I can't figure out why the name NUMS (the form's variable name) is being rendered in the HTML. :( -
Deselection in django forms
Is that possible to deselect selected object in forms.SelectMultiple in Django? My model instance accept the field be None, but when in form i select some object I can't deselect it. -
Django FieldError : Cannot resolve keyword 'total_sales' into field
This is the query I am running to get Total Sales for each party. Party.objects.annotate(total_sales=Sum('sales__salestransaction__total_cost')) It shows correct results. But when I try to apply in my view with get_queryset, it is not working and shows a FieldError which is: Cannot resolve keyword 'total_sales' into field. Choices are: party_address, party_id, party_name, party_phone, sales My View class PartyListView(ListView): paginate_by = 2 model = Party template_name = 'mael/parties.html' def querystring(self): qs = self.request.GET.copy() qs.pop(self.page_kwarg, None) return qs.urlencode() def get_queryset(self): qs = super().get_queryset() if 'q' in self.request.GET: search_txt = self.request.GET['q'] qs = qs.filter(party_name__icontains=search_txt).annotate(total_sales=Sum('sales__salestransaction__total_cost')) return qs.order_by('total_sales') def get(self, request): form = PartyForm() party_list = self.get_queryset() qrstring = self.querystring() paginator = Paginator(party_list, 5) page_number = request.GET.get('page') party_list = paginator.get_page(page_number) return render(request, self.template_name, {'form': form, 'party_list': party_list, 'querystring': qrstring}) Models class Party(models.Model): party_id = models.BigAutoField(primary_key=True) party_name = models.CharField(max_length=128) party_phone = models.CharField(max_length=128) party_address = models.CharField(max_length=128) def __str__(self): return self.party_name class Sales(models.Model): invoice_no = models.BigAutoField(primary_key=True) invoice_date = models.DateField(default=date.today) party = models.ForeignKey(Party, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) class SalesTransaction(models.Model): sales = models.ForeignKey(Sales, on_delete=models.CASCADE) item_qty = models.PositiveIntegerField(default=0) total_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name What is a problem with the get_queryset function and how can I solve this error? Please help. -
Create database using docker-compose django
I have a Django application that is dockerized and using Postgres for the database and I want that every time someone builds the docker-compose so the app should create the database inside db container if the database is not already existed there, and also I have some static data inside some tables and I want to insert that data if the same data doesn't exist in the tables. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - dev.env ports: - "5432:5432" app: container_name: app build: context: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./core:/app - ./data/web:/vol/web env_file: - dev.env ports: - "8000:8000" depends_on: - db volumes: postgres_data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # COPY ./core /app WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] /scripts/run.sh #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami python manage.py … -
Error The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'
I have 3 model. 2 model for creating user. 1 model get primary key from user model my model class CustomUser(AbstractUser): user_type_data=((1,"AdminHOD"),(2,"Managers"), (3,"Teamleaders"),(4,"Admins"),(5,"Supports"), (6,"Callers"),(7,"Fields"),(8,"Tester") ) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) class Callers(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) gender=models.CharField(max_length=225) profile_pic=models.FileField() address=models.TextField() team_id=models.ForeignKey(ListofTeam,on_delete=models.CASCADE,default=1) group_id=models.ForeignKey(ListofGroup,on_delete=models.CASCADE,default=1) objects=models.Manager() class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="admin.username") my error when i makemigrations testwebsite.report.nhan_vien: (fields.E312) The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'. I try username only class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="username") It still error testwebsite.report.nhan_vien: (fields.E312) The to_field 'username' doesn't exist on the related model 'testwebsite.Callers'. How can I get username as to_field in model Thanks for your reading -
How to add the same data to list of users?
Let us suppose the I have list 10000 Users in my website And there field "new_notification" (just for example) Now i want a certain notification to the every user in the list not for in the other users data. let us suppose list user = ['user1','user2',] data= 'new post is out' Now one way is this for i in user: i.data = data i.save() But according this is time consuming for 10000 running the for loop is not good according if i am wrong then please correct. I hope you understand my problem Is there more fast alternative of for loop? Thanks in advance. -
when am working on a formA, How i can get a value of a field from modelB after select a Many2Manyfield of a modelB on Django
I have modelA that contain some fields,one of the those fields is type "ManyToManyField"(call another modelB that has 3 fields, one of them defined as"sigma"), the story that in the formA I want when i select option from the ManyToManyField(modelB) , I get the value of sigma of this ManyToManyField selected. enter image description here ---> I have tried to do that but always i get the last value of the sigma(get the sigma from last example added on the admin page of the modelB) entered on the admin page and not the value of sigma that correspond the many2manyfield selected by the user. **PS:**the data of the modelB i have added it throw the admin page to be displayed when i work with the formA on my localhost. Here is the code in the models.py: code of the ModelA: class ModelA(models.Model): description = models.CharField(verbose_name=" Description ", max_length=60) modelelement = models.CharField(verbose_name=" Mode Element ", max_length=60) element = models.ManyToManyField(ModelB) code of the ModelB in the models.py: class ModelB(models.Model): designation = models.CharField(verbose_name="designation", max_length=60) resistance = models.CharField(verbose_name='resistance W', max_length=50) sigma = models.FloatField(verbose_name='Sigma', max_length=50) def __str__(self): return self.designation + " " + self.resistance in forms.py : class ModuleForm(ModelForm): class Meta: model = ModelA fields … -
Django Authentication without Django Admin functionality
I am working on a Rest API using Django Rest Framework. I want to add registration and authentication, but I don't know how to do it. There is a bunch of methods of doing that in official docs, but they all seem to be using Django Admin functionality (by inheriting their User classes from AbstractBaseUser), which I don't want to use. I want to do it from scratch, have my own Person class which does not use any Django Admin functionality. I am planning to disable Django Admin in my project. Is there a way to do that? -
Django - How can I send absolute url for a model from views.py to another python script?
I'm pretty new to Django and am trying to make a breadcrumbs module. It works pretty well, except I'm having trouble trying to link back to URLs which need a primary key. I've got a breadcrumbs.py file which simply looks up the list of keywords in a list and adds HTML in the form of list items. The problem is to link back to, for example, the profile of a user, I need to send the absolute_url for that profile to breadcrumbs.py. However, since I'm calling the get_breadcrumbs function from within views.py, I can't directly send the request object as an argument in extra context. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.SET_DEFAULT, blank= True, default=Role.get_default) image = models.ImageField(default='profile_pics/default.png', upload_to = 'profile_pics') def __str__(self) -> str: return f"{self.user.username}'s profile" def get_absolute_url(self): return reverse("profile", kwargs={"pk": self.pk}) views.py: from apps.backend_utils.breadcrumbs import get_breadcrumbs class ProfileView(LoginRequiredMixin, DetailView): model = Profile template_name = 'users/users_profile.html' extra_context = { 'breadcrumbs': get_breadcrumbs(['home']), 'page_title' : 'Profile', } breadcrumbs.py: from django.urls import reverse_lazy breadcrumb_lookup = { 'home': { 'title' : 'home', 'url_name': 'home', 'icon_class' : 'fas fa-home', }, 'profile': { 'title' : 'Profile', }, ...[Code omitted]... } for k, v in breadcrumb_lookup.items(): if 'url_name' in v.keys(): v.update({'url': … -
Problem with Select a valid choice. That choice is not one of the available choices
in my form.py I have a class StudentsForm: class StudentsForm(ModelForm): def __init__(self, *args, **kwargs): students = kwargs.pop('students ') course = kwargs.pop('course ') super().__init__(*args, **kwargs) CHOICE_LIST = [('', '----')] i = 1 for itm in students: CHOICE_LIST.append((i, itm)) i += 1 self.fields['students'].choices = CHOICE_LIST self.fields['students'].initial = [''] self.fields['course'].choices = [(1, course), (2, '----' )] self.fields['course'].initial = [1] class Meta: model = StudCourse fields = ( 'course', 'students', ) widgets = { 'course': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Select course', 'style': 'color: crimson; background-color:ivory;' }), 'students': forms.SelectMultiple(attrs={'class': 'form-control' , 'placeholder': 'Select students', 'style': 'color: crimson; background-color:ivory;' }), } my view.py def test(request): #team = get_team(request) # here the second students is a query set of model Student, 2nd course is an object of model #Course form = StudentsForm(students=students, course=course) if request.method == 'POST': form = StudentsForm(request.POST, students=students, course=course) if form.is_valid(): form.save() return redirect('home') if team.exists(): return render(request, 'app/students_goal_form.html', {'form':form}) my students_goal_form.html {% block content %} <section id="students_form"> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <div class="col-3"></div> <div class="col-6"> <div class="form-group"> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success"> <i class="icon-circle-arrow-right icon-large"></i> Save </button> </form> </div> </div> <div class="col-3"></div> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> … -
Django Rest Framework how to check an object is exists or not?
I'm trying to check if an object is exists or not and this is how I do: try: control = Card.objects.filter(cc_num = cc_number)[0] exists = True except (IndexError): exists = False It works but I wonder if there is a more practical way to do? (The reason I use except(IndexError) is I'm finding the object with typing [0] to end of model.objects.filter().) -
Neomodel: ValueError: Can't install traversal 'source' exists on NodeSet
enter image description here I used django_neomodel to connect the Neo4j graph database. The graph data in Neo4j database is above which is the relationships between genes. This is my model for data. class Genes(StructuredNode): id = StringProperty() name = StringProperty() source = Relationship('Genes', 'Interaction') target = Relationship('Genes', 'Interaction') When I run len(Genes.nodes) in python shell, it throws an error: Traceback (most recent call last): File "<console>", line 1, in <module> File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\util.py", line 344, in __get__ return self.getter(type) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\core.py", line 266, in nodes return NodeSet(cls) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\match.py", line 581, in __init__ install_traversals(self.source_class, self) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\match.py", line 172, in install_traversals raise ValueError("Can't install traversal '{0}' exists on NodeSet".format(key)) ValueError: Can't install traversal 'source' exists on NodeSet Anybody knows why? -
How to get the instance of a model from inlines in django ModelAdmin
Example: Suppose I have two models: from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=5, default='admin') def __str__(self): return self.name class Book(models.Model): active = models.BooleanField(default=True) name = models.CharField(max_length=5, default='admin') author = models.ForeignKey(Author, null=True, on_delete=models.CASCADE) upload = models.FileField(upload_to ='uploads/', null=True) def __str__(self): return self.name And this is my admin setup: from django.contrib import admin from .models import Author, Book class BookInLine(admin.StackedInline): model = Book extra = 0 @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['name'] inlines = [BookInLine] def get_inline_object(self, request): inlineObject = self.get_inline_instances(request)[0] #this gives me access to BookInLine object. #an example of what I need to get is: return inlineObject.instance The problem is, ModelInLine objects have no attribute instance associated with them. I can get the parent instance, that is the instance of the Author model by writing the following method in the BookInLine class: def get_parent_object_from_request(self, request): resolved = resolve(request.path_info) if resolved.kwargs: return self.parent_model.objects.get(pk=resolved.kwargs["object_id"]) return None this will give me the instance of the Author model, what I need is to access the instance of Book model associated with that change_view. I can't get any info on how to do that? Can someone please help me with this? -
Django getting data from database using foreign key
I am working on a django blog app and i want to access all the fields of database through foreign key of other database . class User(AbstractUser): about_user = models.TextField(("Profile"),blank = True) def __str__(self): return self.username class Post(models.Model): author = models.ForeignKey("account.User",on_delete=models.CASCADE) status = models.BooleanField(("Status"),default = False) Now I want to access all the data of user database from post something like posts = Post.objects.filter(status = True) posts.author.about_author or user = User.objects.filter(username = post.author) user.about_author what i am trying here in my template all the content of post will display and after that i want the about_author (whoever wrote the post ).kinda like how stackoverflow shows every questions. Thanks in advance and any advice would be much appreciated. -
My first app with django for books autors
I am totaly new with django and i'm trying to create (for learning) a webapp like this:To my site first i need to connect. Once connected i see searche bar and a create option. For searche i use an intenger. I would like to create autors. Foe each autor an id. When i searche for an id i get the autor page with all his informations. On the bottom of the page i have links. One where i can add the autors book. One wher i can add resumes and the last link i can add comments. Can someone give me somme clous how to create this webapp? TNX all!! -
Product() got an unexpected keyword argument 'product_price'
I have created a fruit selling website in django and i got the following error, Error Photo my views file is as under, def seller_add_product(request): if request.method=="POST": seller=User.objects.get(email=request.session['email']) Product.objects.create( seller=seller, product_name=request.POST['product_name'], product_price=request.POST['product_price'], product_image=request.FILES['product_image'], product_desc=request.POST['product_desc'], ) msg="Product Added Successfully" return render(request,'seller_add_product.html',{'msg':msg}) else: return render(request,'seller_add_product.html') My model file is as under, class Product(models.Model): seller=models.ForeignKey(User,on_delete=models.CASCADE) product_name=models.CharField(max_length=100) prodcut_price=models.PositiveIntegerField() product_image=models.ImageField(upload_to="product_images/") product_desc=models.TextField() def __str__(self): return self.seller.name+"-"+self.product_name now whats wrong, pls help -
Is it possible to use docker-compose for ecs farget deployment by cdk?
Current, my source code is here below export class CdkFargateStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const cluster = new ecs.Cluster(this, "SampleCluster", { clusterName: "SmapleCluster" }); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef"); const container = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app"), memoryLimitMiB: 512, cpu: 256 }); container.addPortMappings({ containerPort: 3000 }); const ecsService = new ecs.FargateService(this, "Service", { cluster, taskDefinition, desiredCount: 2 }); const lb = new elb.ApplicationLoadBalancer(this, "LB", { vpc: cluster.vpc, internetFacing: true }); const listener = lb.addListener("Listener", { port: 80 }); const targetGroup = listener.addTargets("ECS", { protocol: elb.ApplicationProtocol.HTTP, port: 3000, targets: [ecsService] }); new cdk.CfnOutput(this, "LoadBalancerDNS", { value: lb.loadBalancerDnsName }); } } It build the Dockerfile under app directory (app/Dockerfile) and It works well. However now I want to use two docker written in docker-compose.yml, Dockerfile.django and Dockerfile.nginx are built in docker-compose. There are files app/docker-compose.yml app/Dockerfile.nginx app/Dockerfile.django Different from Dockerfile, it makes two docker image. So my idea is 1) Ignore docker-compose.yml and make two containers somehow? (I want to indicate the docker file name though,,) const container1 = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app/Dockerfile.django"), memoryLimitMiB: 512, cpu: 256 }); const container2 = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app/Dockerfile.ngingx"), memoryLimitMiB: 512, cpu: 256 }); I can use … -
when i trying to object.save() i got an error "missing 1 required keyword-only argument: 'manager'" in django
when i trying save something in views . get an error , " post_obj.save() TypeError: __call__() missing 1 required keyword-only argument: 'manager' " models.py class Post(models.Model): title = models.CharField(max_length=150) owner = models.ForeignKey(Customer, on_delete=models.CASCADE) views.py @api_view(["POST"]) def create_post(request): if request.data != {}: id = request.data["customer_id"] title = request.data["title"] user = Customer.objects.filter(id=id) if user.count() != 0: post_obj = Post(owner=user, title = title) post_obj.save() then i get this error . how can i fix this error ? -
Django - Diplay a form in a modal
I'm building a Django application and I try to display one of my forms in a modal window. It has been initially developed for a normal one, the scripts worked fine, but I cannot manage implement properly the modal. The context is classical: a window displays a list of objects with, for each of them, a button to edit it, and an additional global button to create a new object. Each button is supposed to open the same modal. It could have become easy if I did not have several js scripts dedicated to the form, because they are my issue: the do not work properly now that the form is in a modal. So there is something I did wrong, and at the end I'm not even sure my approach is the best one. The modal is displayed using bootstrap, HTML code is the following: <div id="grp_detail" class="modal fade hide" role="dialog" tabindex='-1'> <div class="modal-dialog modal-lg"> <div class="modal-content form_content"> {% include './adm_group_detail.html' %} </div> </div> </div> Tell me if you need the included template - it's quite big because the form is a bit tricky. The view that displays de page with the list is the following: @user_passes_test(lambda u: u.is_superuser … -
Define email subject in a Django template
Say I want to send an email using the send_mail() method. The body of the email lives in templates/email.html. I would like to define the email subject in the same file to keep things in one place. But send_mail() needs the subject in a separate variable. So I came up with an ugly hacky way to do it. I start the template like this: {% comment "The second line of this template will be used as email subject" %} Congratulations, your account was created! {% endcomment %} And then extract it in the code like this: template = loader.get_template('email.html') subject = template.template.source.splitlines()[1] This works, but I dislike this solution. Is there an easier and more readable way to do this? More generally, can I define a variable in Django template and then extract it in the application? Something like template.get_variable("email_subject")? -
django-cors-headers does not allow a request from an allowed origin
The problem that I am facing is that I cannot fetch an existing user from my NextJS frontend. The backend framework that I use is Django (along with the django-cors-headers package). django-cors-headers does not allow a certain HTTP request, while it should. My next.config.js contains a rewrite, so that I can access my backend. async redirects() { return [ { source: '/api/:path*', destination: 'http://localhost:8000/:path*/', permanent: true, }, ] }, And my django-cors-headers settings look like this: # CORS CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:8000', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', ] CORS_ALLOW_ALL_ORIGINS = True The request that fails attempts to fetch a user with an ID of 1. This user exists and therefore, this request should succeed. fetch(`/api/users/${String(userId)}/`, { mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json', }, }) However, the only thing that I get back from the request is an error message about CORS. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/users/1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301. It looks like my django-cors-headers setup is wrong. But I am allowed to obtain my JWT tokens. The following request succeeds. fetch('/api/token', { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/json', }, … -
Why the data is not being saved in another model?
class AdvancePaymentCreateSerializer(serializers.ModelSerializer): PAYMENT_MODE = ( ("cash", "Cash"), ("cheque", "Cheque"), ("upi", "UPI"), ("imps", "IMPS"), ("neft", "NEFT"), ("rtgs", "RTGS"), ("demand_draft", "Demand Draft"), ) STATUS = ( ("pending", "Pending"), ("hold", "Hold"), ("completed", "Completed"), ("canceled", "Canceled"), ) center = serializers.PrimaryKeyRelatedField(queryset=center_models.Centers.objects.all(), many=True) payment_date = serializers.DateField(required=False, allow_null=True) amount = serializers.FloatField(required=False, allow_null=True) payment_mode = serializers.ChoiceField(choices=PAYMENT_MODE) cash_receipt_no = serializers.CharField(max_length=100, required=False, allow_null=True) invoice_no = serializers.CharField(max_length=100, required=False, allow_null=True) remarks = serializers.CharField(max_length=255, required=False, allow_null=True) status = serializers.ChoiceField(choices=STATUS) center_balance = serializers.FloatField(required=False, allow_null=True) payment_receipt = serializers.FileField(required=False, allow_null=True, allow_empty_file=False, use_url=True) is_active = serializers.BooleanField(default=True) class Meta: model = package_models.AdvancePayment fields = "__all__" def create(self, validated_data): center = validated_data.get("centre") payment_date = validated_data.get("payment_date") amount = validated_data.get("amount") payment_mode = validated_data.get("payment_mode") cash_receipt_no = validated_data.get("cash_receipt_no") invoice_no = validated_data.get("invoice_no") remarks = validated_data.get("remarks") status = validated_data.get("status") center_balance = validated_data.get("center_balance") payment_receipt = validated_data.get("payment_receipt") is_active = validated_data.get("is_active") obj = package_models.AdvancePayment.objects.create( center=center, payment_date=payment_date, amount=amount, payment_mode=payment_mode, cash_receipt_no=cash_receipt_no, invoice_no=invoice_no, remarks = remarks, status = status, center_balance = center_balance, payment_receipt = payment_receipt, is_active = is_active ) ledger = package_models.CollectionCenterLedger( ledger_type="credit", amount=amount, center_id=center, remarks="Advanced Amount by Center" ).save() center=center_models.Centers.objects.get_or_create(id=center).first() center.rcl_amount =float(center.rcl_amount) + float(amount) center.save() obj.center_balance =center.rcl_amount obj.save() ledger.center_rem_balance=center.rcl_amount ledger.save() obj.save() return obj This is create serializer of AdvancePayment Model. While creating object in this model i also want to save data in CollectionCenterLedger Model.But while doing this the data … -
django not finding redirect page
hey guys i have the following codes, I'm trying to redirect the GoalUpdate view to GoalPageView , but I get the following Error: Reverse for 'Goals.views.GoalPageView' with keyword arguments '{'kwargs': {'username': 'admin', 'goal_id': '1'}}' not found. 1 pattern(s) tried: ['people/(?P[^/]+)/goals/(?P<goal_id>[^/]+)/\Z'] My URLs urlpatterns = [ path('<username>/goals/',GoalsView,name='Goals'), path('<username>/goals/<goal_id>/',GoalPageView,name='Goal Page'), path('<username>/goals/<goal_id>/update/',GoalUpdate,name='Goal Update'), ] My Views: def GoalPageView(request,username,goal_id): some view code return render(request,'goal_page.html',context=context) def GoalUpdate(request,username,goal_id): Some View Code return redirect(GoalPageView,kwargs={'username':username,'goal_id':goal_id}) -
I cant create a page with an empty path in Django
centralsite/views def centralsite(request): return render(request, 'centralsite/text.html', {}) centralsite/urls from django.urls import path from . import views urlpatterns = [ path('', views.centralsite, name='centralsite'), ] urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [path(' ', include('centralsite.urls')), path('polls/', include('polls.urls')), path('admin/', admin.site.urls),] error message is: Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^$ polls/ admin/ The empty path didn’t match any of these. how do i make this empty path work? -
Django Dependent Dropdown List not displaying
my dropdown list is not getting displayed. Not only the filtered value but the whole doctor_dropdown.html. Is there some problem my Ajax? The thing that i want is that when a patient clicks on neurology dropdown list the doctors are to be displayed should be a neurologist only. HTML AND SCRIPT <div class="loginContainer" id="signupContainer"> <div class="img"> <img src="{% static 'image/booking.svg' %}"> </div> <div class="login-content"> <form method="POST" id="signupForm" data-doctor-url="{% url 'ajax_load_doctor' %}"> {% csrf_token %} <h2 class="title">Booking form</h2> {% for d in patient_details%} <div class="input-div one"> <div class="i"> <ion-icon name="person-circle"></ion-icon> </div> <div class="div"> <h5>Patient ID: PID - {{d.id}}</h5> <input type="hidden" name="PatientID" value="{{d.id}}"> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="person"></ion-icon> </div> <div class="div"> <h5>Name: {{d.FirstName}} {{d.LastName}}</h5> </div> </div> {% endfor %} <div class="input-div one" id = "bookingField"> <div class="i"> <ion-icon name="business"></ion-icon> </div> <div class="div"> <div class="custom-select"> <select name="Department" id="Department" required> <option value="General">Select a Department</option> //department part {% for d in department_details%} <option value="{{d.id}}">{{d.name}}</option> {% endfor %} </select> </div> </div> </div> <a href="doctors" id="bookingMoreBtn" class="section-btn btn btn-default btn-blue smoothScroll">Visit our Departments</a> <div class="input-div one" id = "bookingField"> <div class="i"> <ion-icon name="medkit"></ion-icon> </div> <div class="div"> <div class=""> <select name="doctor" id="doctor" required> //doctors to be displayed here </select> </div> </div> </div> <a href="doctors" …