Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
update fields in a table of instances and had a default value
I m trying to had a template in which I populate list of payables and a field I can fill in with an amount I want to pay for each invoice this is my code: forms.py # class form without a model class paymentForm(forms.Form): #Note that it is not inheriting from forms.ModelForm number = forms.CharField(max_length=20) clientid = forms.IntegerField(widget=forms.HiddenInput()) clientname = forms.CharField(max_length=50) duedate = forms.DateField() montant = forms.DecimalField(max_digits=12, decimal_places=2) solde = forms.DecimalField(max_digits=12, decimal_places=2) payment = forms.DecimalField(max_digits=12, decimal_places=2, initial=0) def __init__(self, *args, **kwargs): super(paymentForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['number'].widget.attrs['readonly'] = True self.fields['clientname'].widget.attrs['readonly'] = True self.fields['duedate'].widget.attrs['readonly'] = True self.fields['montant'].widget.attrs['readonly'] = True self.fields['solde'].widget.attrs['readonly'] = True views.py with first line is a query and payables is a dictionary of payables (it works fine. but in this dictionnary payment field is not present as I just want to populate it in my template def updatepayables(request): count, payables = Payablesquery() form = paymentForm() # manage save if request.method == "POST": form = UpdateClientForm(request.POST) pass return render(request, 'payment/updatepayables.html', { "form": form, "payables": payables}) my template: <div class="container"> <h2>{{title}}</h2> <table class="table"> <thead> <tr> <th>client Name</th> <th>duedate</th> <th>number</th> <th>montant</th> <th>solde</th> <th>payment</th> </tr> </thead> <tbody> <form method="post" action=""> {% for payable in payables %} … -
Django: Is it possible to use a user model value as a db_table name
I am trying to assign each user a database table based on their location. I tried the following in my app and user models.py files. user models.py from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) zip_code = CharField(_("zip code"), max_length=5, default="78661") def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) app models.py from django.db import models from project1.users.models import User zipcode =User.objects.filter(zipcode=User.zip_code) class Data(models.Model): index = models.BigIntegerField(blank=True, null=True) temperature_surface = models.FloatField(db_column='Temperature_surface', blank=True, null=True) wind_speed= models.FloatField(db_column='Wind_speed_gust_surface', blank=True, null=True) class Meta: managed = False db_table =zipcode There are two problems I have with this method. I get the following attribute error for zip_code even though I am able to store the users zipcode in that variable. zipcode =User.objects.filter(zipcode=User.zip_code) AttributeError: type object 'User' has no attribute 'zip_code' The second problem is identifying which user is logged in and assigning that value to the db_table = zipcode. Is there a better way to accomplish this? I would ultimately like for the db_table value to match the users zip code. -
Best hosting solution for Django application with low volume but large storage needs
I'm developing a Django app for an archaeological database. The actual traffic to the site will be very small (think 100 unique visitors a day) so using a cheap low powered VPS seems sufficient. But there is a very large amount of media (photos/pdfs) to host and make available. Looking at Digital Ocean and Amazon (EC2 + EBS) seems to make hosting large amounts of content very expensive. Is there an answer for low powered large volume hosting? -
django: Primary key issue when saving modelform into postgresql
I have a model with au autofield, which has the primary key as such: class historical_recent_data(models.Model): id = models.AutoField(primary_key=True, auto_created = True) Id = models.CharField(max_length=100, verbose_name= 'references') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) def __str__(self): return self.reference Now, when I want to input data into the db table with a form in template, Django tries to give the id field a 1 value resulting in the following error: duplicate key value violates unique constraint "dashboard2_historical_recent_data2_pkey1" DETAIL: Key (id)=(1) already exists. there is more than 11,000 values in this db table, why django does not automatically generate the pk to be 11,001 when a new form is being posted into the table? -
How to make dynamic listdir in Django forms?
I need to be able to pick files from server using forms. Now im using os.listdir but its doesn't actualize when new file in folder shows up. List is updating only on server reboot. How can I make updating list of files without server restart? Thanks Im using Python 2.7 and Django 1.7. forms.py class OutFileForm(forms.Form): file_list = os.listdir(PATH) file_list_done = [("", "---")] for element in file_list: file_list_done.append((element, element)) outbound_file = forms.ChoiceField(label="Outbound", choices=file_list_done, required=True) -
How to hide and show SummerNote toolbar in response to focus and blur events
How do you hide or show the SummerNote toolbar in response to focus or blur events? I have a few forms with 3 or more textareas and I'd like to see the toolbar only on the focused area. I'm using Bootstrap and SummerNote on Django forms. I've tried with: // Select all textarea tags in the form var elements = $( "textarea" ); // Loop through all textarea elements for (var i = elements.length - 1; i >= 0; i--) { var element = elements[i]; $( '#' + element.id ).summernote({ airMode: false, // <-- False: Show toolbar; True: Hide toolbar toolbar: [ ['style', ['style']], ['font', ['bold', 'italic', 'subscript', 'superscript', 'clear']], ['color', ['color']], ['para', ['ol', 'ul', 'paragraph']], ['table', ['table']], ['insert', ['hr']], ['view', ['fullscreen']] ], callbacks: { onFocus: function() { $( '#' + this.id ).summernote({ airMode: false }); }, onBlur: function() { $( '#' + this.id ).summernote({ airMode: true }); } } }); } without results -
Call data without for loop from database
how do I call data from the database without the for loop in a HTML file? I'm a beginnger and in all tutorials I could find they use the for loop. But I want to get a url from my database and post it only once in the HTML file, but I dont want to hardcode it in the file. So in my models.py my class looks like this class Weburl(models.Model): source = models.URLField(max_length=200) In my views.py I call this from django.shortcuts import render def index(request): songs = Songs.objects.all() contacts = Contacts.objects.all() url = Weburl.objects.all() context = {'songs': songs, 'contacts': contacts, 'url': url} return render(request, 'index.html', context) Of course you need to import the stuff in views.py. Now I can call the songs, contacts and url in a for loop. But I don't want to call url as a for loop. So what needs to be changed? Other question, does it make senses to save the songs and contacts in the context variable? If anyone knows what to do, it would be great. Thanks in advance. -
I am unable to install django from command prompt. I am attaching the error. please show the path to me
C:\Users\utkarsh>pip install django Fatal error in launcher: Unable to create process using '"c:\users\utkarsh\appdata\local\programs\python\python38-32\python.exe" "C:\Users\utkarsh\AppData\Local\Programs\Python\Python38-32\Scripts\pip.exe" install django': The system cannot find the file specified. -
Django mptt model not linking to parent
Hello I am in the process of implementing a hierarchical location model. I have also created a form to be able to add locations while not using the admin interface. Tp do this I am using mptt's TreeNoeChoiceField. However when I select the correct parent and then submit the new location's parent defaults to none. I am unsure why this is happening and can't seem to find anyone else having similar issues. forms.py class Location Form(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Location.objects.all()) class Meta: model = Location fields = ("name", "description", "directions", "elevation", "latitude", "longitude") -
How to add condition on Django model foreign key?
I am new in Django, would you please help me, I have two models, by name of Continent and Country, in the Country form I want to only display the Continents in the dropdown list which their status is true? models from django.db import models from smart_selects.db_fields import GroupedForeignKey, ChainedForeignKey class Continent(models.Model): name = models.CharField(max_length=255) status=models.BooleanField(default=True) def __str__(self): return self.name class Country(models.Model): continent = models.ForeignKey(Continent, null=True, on_delete=models.SET_NULL) status=models.BooleanField(default=True) name = models.CharField(max_length=255) def __str__(self): return self.name forms class FormContinent(ModelForm): class Meta: model = Continent fields = '__all__' class FormCountry(ModelForm): class Meta: model = Country fields = '__all__' views def continent(request): form = FormContinent() if request.method == 'POST': form = FormContinent(request.POST) form.is_valid() form.save() return redirect('/continent') else: context = {'form': form} return render(request, 'continent.html', context) def country(request): form = FormCountry() if request.method == 'POST': form = FormCountry(request.POST) form.is_valid() form.save() return redirect('/country') else: context = {'form': form} return render(request, 'country.html', context) -
Django-channels: Send message after database update
I'm using django-channels to provide a chat app on websockets. I store messages in a database. I would like to be able to send new messages to the client as soon as they get written to the database. How can I do that? I guess I need to make a WebSocketConstructor that will recieve a post_save signal, but I don't know exactly how to send signals to django-channels consumers. -
Stream PDF file from http response directly to client with Python requests library using client certificate
I'm making a request to an endpoint that returns a PDF as streamable binary. This endpoint uses mutual TLS authentication so when I hit the endpoint I must send a client certificate. To achieve this I am using https://pypi.org/project/requests-pkcs12/ which supports the Python requests library. I would like to download this PDF from the client. Ideally when the end user clicks 'download' it hits the endpoint and directly streams the data and downloads it. I am struggling to do this in one single step. Currently what I'm doing is downloading the PDF to a file, then sending this file back to the client. Writing to the file is slow and I'd like to avoid the download-to-file step and simply send a streaming response back somehow. Is there a way to stream this directly using Python's Request? #hit the mutual tls authenticated endpoint response = post(f'{url}, stream=True, pkcs12_filename=client_certificate_path, pkcs12_password=client_certificate_passphrase) #Write the returned data to a file with open('/tmp/newfile.pdf', 'wb') as f: f.write(response.content) #Send the file back to client with Django's FileResponse return FileResponse(open('/tmp/newfile.pdf', 'rb')) While I am using Django which seems to handle this problem nicely with StreamingHttpResponse, I was unable to get this working as it doesn't allow me to … -
CRUD not able to displaly model instances in template to update
I have an app project. I am able to save instances to the model in the database no problem. But I cannot pull in the instance by pk to the html form to edit and update. please see setup below can anyone provide any guidence or help, as to why this is not happening and how I can resolve? views.py def edit_properties(request, id): properties = Properties.objects.get(pk=id) context = { 'properties': properties, 'values': properties, } if request.method == 'GET': return render(request, 'sub/edit_properties.html', context) -
Regex for match url in Django
I'm trying to match this url with a regexp in django/python (old liferay urls) http://127.0.0.1:8080/documents/34105/35593/prova+(1)+(1).jpg/da459266-ab36-faf1-726d-fc989385b0bd but I cannot decode the filename... This is the regexp that I use: documents/(?P<repo>[0-9]{5,10})/(?P<folder>[0-9]{5,10})/(?P<filename>[])/(?P<uuid>[\w-]+) This is the Pythex link -
How does form_valid work in django? How does it compare to save()?
The describtion of this in docs seems very sparse and unclear to me I am asking here. So what is exactly doing the form_valid method here? From what I understand, it gets triggered with POST method and it is kinda calling save() in the last line. form.instance.entry_author=self.request.user in this line I understand that we are setting the current user to be the author but I dont understand why form referances to instance and also where did the form get from? I suppose its in-built in the form-valid function? class CreateEntryView(CreateView): model = Entry template_name='entries/create_entry.html' fields = ['entry_title','entry_text'] def form_valid(self, form): form.instance.entry_author=self.request.user return super().form_valid(form) -
Django recursive serializing
Let's say I have models like this: class A(models.Model): ...some fields here class B(models.Model): ...some fields here a = models.ForeignKey(A, on_delete=CASCADE) class C(models.Model): ...some fields here b = models.ForeignKey(B, on_delete=CASCADE) ... And I want my API endpoint to return something like this { ...some fields here b: [ { ...some field here c: [{...}, {...} ...] }, { ...some field here c: [{...}, {...} ...] } ... ] } I know I can do something like this: class Bserializer(serializers.ModelSerializer): c = Cserializer(source="c_set", many=True, read_only=True,) class Meta: model = B fields = [...some fields, "c"] class Aserializer(serializers.ModelSerializer): b = Bserializer(source="b_set", many=True, read_only=True,) class Meta: model = A fields = [...some fields, "b"] But if this goes deeper or/and models have more foreign keys it starts to become really complicated. Is there a way to add recursively all instances referencing the model. -
Displaying a ChartJs chart within a bootstrap-modal in Django
I want to display a ChartJs chart within a modal.When I use static datas it is okay and the chart is displayed but by using ajax to get an specific object's datas, it shows just an empty modal. Views.py def getChart(request): if request.method == "GET" and request.is_ajax(): meterId = request.GET.get("meterId") try: meter = Meter.objects.get(meter_id=meterId) except: return JsonResponse({"success": False}, status=400) context = Report.objects.filter(meter=meter) return JsonResponse(context,safe=False) return JsonResponse({"success": False}, status=400) HTML $(".chart").click(function(e){ e.preventDefault(); var meterId = name; var data = {meterId}; $.ajax({ type : 'GET', url : "{% url 'get_chart' %}", data : data , headers: { 'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content') }, success : function(response){ console.log(response) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for each in power_data %}'{{ each.time }}',{% endfor %}], datasets: [{ label: "Power Consumption", data: [{% for each in power_data %}'{{ each.power }}',{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)' ], borderWidth: 1 }] } }) }, error : function(e){ console.log(e) } }) }) I checked all parts so many times and also ajax call is doing well and there is no errors.Any ideas? Kind regards. -
Docker-compose: db connection from web container to neo4j container using bolt
I'm working on django project with neo4j db using neomodel and django-neomodel. I'm trying to containerize it using docker-compose. when I build the images everything seems fine, but any connection from web container to db using bolt is refused. although I can access the neo4j db from the browser on http, and even from local machine on bolt. this is the error I get: neo4j.exceptions.ServiceUnavailable: Failed to establish connection to ('127.0.0.1', 7688) (reason 111) I'm using the following configs: <pre>Django == 3.1.1 neo4j==4.1.0 neomodel==3.3.0 neobolt==1.7.17 </pre> this is my docker-compose file: version: '3' services: backend: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - neo4j_db networks: - mynetwork links: - neo4j_db neo4j_db: image: neo4j:3.5.17-enterprise ports: - "7474:7474" - "7688:7687" expose: - 7474 - 7687 volumes: - ./db/dbms:/data/dbms environment: - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes - dbms.connector.bolt.listen_address=:7688 - dbms.connector.bolt.advertised_address=:7688 networks: - mynetwork networks: mynetwork: driver: bridge and here's connection configs in django settings: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:pass@123@127.0.0.1:7688') Thanks in advance.. -
Is there a way to call a function on a model field?
I have a model which has a FileField and I now need to call an API to convert the file. Not sure on how to implement the function and also, how to show the file to the user after it's converted. I was thinking of calling the function on each model object and then just changing the url in the model to the new file. Is there a way to call the function before the file is saved to the DB to make things easier? I'm not sure if this is possible because I'm guessing that the file must be saved before it's converted. -
Django views in modules in "views" package, call by module name - Namespacing problem
My views.py is getting large, and I'd like to organize different parts of my django website by functionality. I envision something like this: urls.py views ├── __init__.py ├── editor.py └── display.py In my urls.py I'd like to have seperated namespaces like this: url(r'^display_some_post/$', views.display.post, name="display_post"), url(r'^edit_some_post/$', views.editor.post, name="editor_post"), Note that every view is called by it's module name. But I can't quite figure out the correct way to set up init.py and / or import the modules into the urls.py. Any help is appreciated! -
Django with Angular - relative paths when font and back have different url
After two days I failed to setup (any form of) webpack working with django3 in the back and angular10 in the front, so I decided to just use gulp to start ng serve for frontend and python manage.py runserver for backend. I am new to this, so this is probably very stupid but really two days is a lot of time to give on setup and get nothing back .. Currently I am trying to call an API on the django server that is on http://127.0.0.1:8000 while ng serve is running on http://127.0.0.0:4200 @Injectable() export class EchoService { constructor(private httpClient: HttpClient) {} public makeCall(): Observable<any> { return this.httpClient.get<any>( 'http://127.0.0.1:8000/my-api/' ); } } ''' Is there a better way how to do this in Angular without using "http://127.0.0.1:8000" in every component call I do? How can I make it as close as possible to relative paths, that will be used in the prod version of this (for prod I will just put the bundles manually in the html, but I can not do that manually for dev) -
(1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'")
i have been making some changes on my model 'lesson' and suddenly i couldn't use my model on my django website with MySql data base. when i try to use it on a view i got this error (1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'") the commands makemigrations and migrate works fine but this error occurs when using the model only this is the model.py from django.db import models from .validators import * from scolarité.models.level import Level from scolarité.models.subject import Subject class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) def __str__(self): return self.lesson views.py #=========================== view lessons ===================== @login_required #use this to make the view accessible for logged in users only def view_lessons_list(request,subject_id): request.session['subject_id']= subject_id #assign subject id value to session level = Level.objects.get(id=request.session['level_id']) #getting the level model subject = Subject.objects.get(id=request.session['subject_id']) #getting the subject model lessons = Lesson.objects.filter(subject=subject ,level=level) #filtering the lesson based on the chosen level and subject context={'lessons':lessons,} return render(request,'leçon/view_lessons_list.html',context) the traceback Traceback (most recent call last): File "C:\Users\YAHYA-PC\Desktop\CourseCode\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File … -
Comment section in django blog won't show up under each individual post?
The comment successfully saves in the django admin but won't show up on the actual site. Here is the comment model: class comment(models.Model): linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE) commentauthor = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) This the html code for the blog home. the post for loop goes through all the post objects and prints them out. I created a comment loop to loop through all the comments for the linked post and print. Is the problem in my html code? {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div> <h2>Comments</h2> {% for cmnts in linkedpost.postcomments %} #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a> <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small> <p class="article-content">{{ cmnts.body }}</p> {% endfor %} </div> </div> </article> {% endfor %} -
How to set a maximum no. for a Coupon can be used in Django Project
I have set a Coupon Payment System for my E-commerce project but I want to set a maximum no. of usage for this coupon for maximum 10 times. How do I do that? Here is the models.py class Coupon(models.Model): code = models.CharField(max_length=15,unique=True) amount = models.DecimalField(decimal_places=2, max_digits=100) valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.code Here is the views.py class AddCouponView(View): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) coupon_qs = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now,active=True) order_coupon = Order.objects.filter(coupon=coupon_qs.first(), user=self.request.user) if order_coupon: messages.error(self.request, "You can't use same coupon again") return redirect('core:checkout') if coupon_qs: order.coupon = coupon_qs[0] order.save() messages.success(self.request, "Successfully added coupon") return redirect('core:checkout') else: messages.error(self.request, "Coupon Does not Exists") return redirect('core:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('core:checkout') Here is the forms.py class CouponForm(forms.Form): code = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Promo code', 'aria-label': "Recipient's username", 'aria-describedby': "basic-addon2" })) -
Authenticate function not working in Django
I am trying to authenticate in Django using authenticate but my code is not running and showing errors. My code: def post(self, request): data = request.data username = data.get('name', '') password = data.get('password', '') if not username or not password: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(request, username=username, password=password) if not user: return Response({'Error': 'Invalid name/Password'}) login(request,user) What's wrong in my code? I am getting both username and password from json but it's failing to validate.