Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TypeError: Field 'id' expected a number but got <homeworkForm bound=True, valid=Unknown, fields=(title;descripiton;due)>
I have been trying to allow staff users to post homework to a database however I keep running into the issue above. I've tried setting data['id'] = 0/'' as well as dropped the table and makemigrations/migrate. models.py from django.db import models from teachers.models import Teacher class Homework(models.Model): title = models.CharField(max_length=100) descripiton = models.CharField(max_length=500) due = models.DateField() teacher = models.OneToOneField( Teacher, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title form.py from django import forms class DateInput(forms.DateInput): input_type = 'date' class HomeworkForm(forms.Form): title = forms.CharField(label='Title', max_length=100) descripiton = forms.CharField(label='Descripiton', max_length=500) due = forms.DateField(label='Due', widget=DateInput) views.py def homework(request): if request.user.is_authenticated & request.user.is_staff: if request.method == 'POST': data = request.POST.copy() data['teacher'] = request.user.username request.POST = data print(request.POST) form = HomeworkForm(request.POST) if form.is_valid(): post = Homework(form) post.save() messages.info(request, 'Form sent') print('worked') return render(request, 'index/index.html') else: print('error in form') form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: return redirect('index') -
Django contenttype : Is it possible to create generic relation dynamically without explicitly defining GenericRelation(X) in a model?
Say if we want to define generic relation from Bookmart to TaggedItem, we would define in the model as follow: class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem) and if we want more than one generic relations to models. we would have to explicitly define multiple GenericRelation(x) statements. I was reading Django permissions documentation and stumble upon this code: content_type = ContentType.objects.get_for_model(BlogPost) permission = Permission.objects.create( codename='can_publish', name='Can Publish Posts', content_type=content_type ) As far as I see from the docs, BlogPost doesn't explicitly specify its generic relation(s). How is it doing it? -
Django, ERP/CMS software and E-commerce site on different servers
hope someone can help me with this. I am new to python and django, but already took some tutorials on how to create your own ERP/CMS and eCommerce projects on Django. My questions are... or what I want to do is: I want to install the ERP/CMS in my own local server (also it's gonna be the admin part for the eCommerce site) Install the eCommerce site on a Webhosting server Suppose that you have a business and you manage your operation with the ERP/CMS (inventory, employee, invoicing, etc) software created on Django. Then you realize that you want to create a website and sell online. So you create your eCommerce site on Django and deploy it in your preferred Webhosting. Questions: Considerations: Have to be in 2 separate servers and database For security reasons, both databases can not see each other or have any relation between them. In a situation your site gets hack, your primary database(ERP/CMS) will not be compromised. On the eCommerce site, the info the will be upload are Category, subcategory, products(description, attributes, availability[quatity > 0]), image, selling price, client, address. I know that Django can handle multiple databases. What will be the easiest and efficient … -
When I am writing the URL in browser the URL is not working- only the admin page is ascessed . Please show me a path
The name of my project is firstproject and web application is testapp. I am attaching urls.py , views.py and installed apps ` `` from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('hello/',views.greeting), path('admin/', admin.site.urls), ] from django.shortcuts import render from django.http import HttpResponse def greeting(request): s="<h1> hello this is greeting page</h1>" return HttpResponse(s) INSTALLED_APPS = [ 'testapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
_wrapped() missing 1 required positional argument: 'request': Issue with method decorator. (Django, Ratelimit Library)
I am attempting to use a method decorator so I can apply a decorator to the get_queryset method. My main goal is to limit the number of GET requests per minute to avoid query spam. Although, the problem is the decorator keeps throwing an error as written in the title. I've tried switching the order of and adding the self and request parameters, but so far no luck. Thanks! Ratelimit Library: https://django-ratelimit.readthedocs.io/en/stable/usage.html (Ctrl-F to class-based views section.) class ConnectMe(ListView, LoginRequiredMixin): model = Profile template_name = 'users/connect_me.html' context_object_name = 'profiles' paginate_by = 10 @method_decorator(ratelimit(key='ip', rate='1/m', method='GET')) def get_queryset(self): # original qs qs = super().get_queryset() .... -
Django Rest Framework & React Js ( Axios API Request ): After Incorrect authentication attempt, api returns 400
I'm creating a login system and basically, I have two inputs, one for username and the other for password. So when the user enters the correct credentials the API returns 200 response with some data but after incorrect credentials the django-rest-framework marks the request as 400 Bad Request and returns the response with 400 status code and no data, but this happens only when I'm sending a request from react js, after trying bad credentials from postman, the API returns: { "non_field_errors": [ "Incorrect credentials" ] } My Axios code: axios.post('http://192.168.0.29:8000/api/auth/login', { headers: { 'Content-Type': 'application/json' }, username: username, password: password }) .then((response) => { console.log(response.data); }) .catch(err => { console.log(err.data) alert('zjbs eroras') }); } -
What is the difference between the __lte and __gte in Django?
I am trying to figure out the difference between the __lte and __gte in Django. The reason being that I am trying to create a function with dates that can work only with a time frame, so I've been researching between Field Lookups Comparison. I've looked up several documentations https://docs.djangoproject.com/en/3.0/ref/models/querysets/#exclude but didn't reach a conclusive answer. -
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..