Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why on earth does django parse commented html code?
This just cost me like 4 hours. Why on earth does django try to parse tags in commented out html code? -
Django Html Page Rendering Items For Loop
I have a page that I'm running a for loop on and the issues is I only want to show 4 students per column, and then start the next column with the other 4 students. However, I'm struggling getting it to work . I originally had all of this setup correctly, but the second i added the for loop it messed up all the placements of the columns. The code I'm posting is just 4 students in the first column, ill need another 2 columns to display all 12. Truly appreciate the help. Thanks {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2>{% load static %} <img src="{% static 'forms/star.png' %}" alt="chain" height="62" width= "62"> My Classroom</h2> <br> <br> <form action = "/points/k8_points_classroom" method="POST"> {% csrf_token %} <!-- Start Date --> <div class = "container"> <div class = "container"> <div class= 'row'> <div class="col-4"> <p> Recording Data as User : {{user.username}} </p> <p> Today's Date : {{date}} </p> <p> <b> Classroom : {{classname}} </b> </p> </div> </div> <div class="jumbotron" align ="middle"> <h1>My Students</h1> <!-- Line Break --> <hr style="border: 1px solid black;" /> <!-- Line Break --> … -
Playing all songs of a playlist one by one Django
Is there any way I can play all songs that are attached to a playlist using manytomanyField one by one Playlist model: class Playlist(models.Model): image = models.ImageField() name = models.CharField(max_length=100, unique=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) songs = models.ManyToManyField(Music, null=True, blank=True) slug = models.SlugField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('playlist-detail', kwargs={'pk': self.pk}) @classmethod def add_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.add(new_song) @classmethod def remove_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.remove(new_song) and here's how I try to play it: <body onload="cs_change_music('{{object.songs.song.url}}');document.getElementById('song').innerHTML = '{{object.name}}'; document.getElementById('artist').innerHTML = '{{object.artist}}';document.getElementById('cover-image').src = '{{object.image.url}}'"> </body> and it returns unknown as audio source -
List all nullable django model fields
I have a model with both nullable and non-nullable fields. Let's consider an example: from django.db import models class MyModel(models.Model): field_1 = models.CharField(null=False) field_2 = models.CharField(null=True) field_3 = models.ForeignKey(SomeOtherModel, null=True) field_4 = models.ForeignKey(YetAntherModel, null=False) How could I get list of nullable field names (as in example below) from MyModel class? ['field_2', 'field_3'] Right now I have hardcoded mapping which I need to update together with model changes so I'd like to have some generic method for it. Any idea would be appricieated. -
Filter objects with Rest Framework Django API
I have a model Person in Django class Language(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) def __str__(self): return self.name class Country(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) def __str__(self): return self.name class Person(models.Model): PersonId= models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) Countries = models.ManyToManyField(Country) Languages = models.ManyToManyField(Language) each person can have (visit) many countries and have (speak) many languages. I want to create an API that I will send to the endpoint list of few languages and countries, and will return for me the people, which has at their list one of the language and country that I sent. For example I have Person(1,['Portugal', 'Spain'],['portugues','spanish']) , Person(2, ['Portugal', 'Germany'],['portugues','russian']), Person(3,['France', 'Spain'],['spanish', 'french']) I sent data { Countries: ['Portugal', 'France'], Languages: ['russian', 'french'] } so in this case it returns Person2 and Person3. My PersonView with Authentication class PeopleListView(ListAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] def get_queryset(self): return Blog.objects.filter(UserId=self.request.user) Is there any way to do this? I would not like to search by url but send data in body. -
Getting error when changing field-lengt on a ForeignKey to a model not part of HistoricalModel
I use Historical Model in django and need help understanding why change in a non-historical model reference results in DataError Here is my model before and after change: Before: ` from src.lib.db_models import HistoricalModel class NoHistorical(models.Model): id = models.CharField(max_length=1, primary_key=True) class MyHisorical(HistoricalModel): id = models.CharField(max_length=1, primary_key=True) id2 = models.ForeignKey(NoHistorical, on_delete=models.SET_NULL, null=True) ` After: ` from src.lib.db_models import HistoricalModel class NoHistorical(models.Model): id = models.CharField(max_length=2, primary_key=True) class MyHisorical(HistoricalModel): id = models.CharField(max_length=1, primary_key=True) id2 = models.ForeignKey(NoHistorical, on_delete=models.SET_NULL, null=True) ` makemigration&migrate id2=NoHistorical.objects.create(id='bb') MyHisorical.objects.create(id=1,id2=id2) Result in: DataError: value too long for type character varying(1) How can this be solved? -
Django deployment on iis server
I have deployed a django application on IIS server. It's running perfectly fine on localhost:8000, on the server. However if the application runs into an error it is displayed on the external devices, and the server exists the runserver command on the server. How can I prevent the sever to exist runserver command and no error is displayed on the external system. -
Django query complex query in one to one field model
I have two models of Student and Parent Student models.py: class StudentInfo(models.Model): admissionNumber = models.BigIntegerField(primary_key=True,default=0) firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) fullName = models.CharField(max_length=50) gender = models.CharField(max_length=20) dob = models.DateField(null=True) classSection = models.CharField(max_length=20) Parent models.py class ParentInfo(models.Model): student = models.OneToOneField(StudentInfo,primary_key=True, on_delete=models.CASCADE) fatherName = models.CharField(max_length=20) motherName = models.CharField(max_length=20) I have a form to search students through their fatherName. So, what I want is to filter those students whose father's name contains 'some name'. I tried this but it resultes in query set of ParentInfo: parentInfo = ParentInfo.objects.all() studentsInfo = parentInfo.filter(parent__fName = fName).select_related('student') -
Django filters with a string variable field
I want to filter a model with a field but I want to pass the field as a string variable. How can I do it? For example: the_field = 'name' TheModel.objects.filter(the_field='Gazelle') What should I replace the_field with? -
how to render django location field by id for each post?
i have a model in django like this : class post (models.Model) title = models.CharField(max_length=120) .. .. location = models.PointField(srid=4326, null=True, blank=True) objects = GeoManager() def unicode(self): return self.title def get_absoulute_url(self): return reverse("post_map", kwargs={ 'id':self.id }) and i want to render location place by id like this: path('post-map//map/',post_map,name='post_map') path('post-map//index/',home_page,name='post_map') def map (request,id): name = serialize('geojson',get_objects_or_404(Post, id=id) return HttpResponse(name,content_type='json') def home_page(request): return render(request,'home_page.html') and home_page.html is: -
When i run command docker-compose stuck at : db_1 | Version: '5.7.28' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL)
i am new here in docker, i am working on django, when i try to run docker-compose up, console stop after this message db_1 | Version: '5.7.28' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) Can anyone please help me what i need to do now to start my project ? -
How to get name respect to the id from different mysql table in django
i have project which submits data of employee, and i have dropdown which gives department list , while submit it takes id of that department. so when i shows that data in table i gets id but i want name of that id which is in department table how can i do that. view.py def managemp(request): employees = Employee.objects.all() department = Department.objects.all() location = Location.objects.all() return render(request, "manageemp.html", {'department': department, 'employees': employees, 'location': location}) form.py class EmpForm(ModelForm): class Meta: model = Employee fields = ["employee_id", "Name", "designation", "department_id", "manager_id", "date_of_joining", "date_of_birth", "location_id", "email", "contact_number", "password", "created_by", "modified_by", "status", "user_type"] class dept(ModelForm): class Meta: model = Department fields = ["department_id", "department_name", "created_by", "modified_by", "status"] html <tbody id="myTable"> {% for employee in employees %} <tr> <td>{{ employee.employee_id}}</td> <td>{{ employee.Name}}</td> <td>{{ employee.designation}}</td> <td>{{ employee.department_id}}</td> <td>{{ employee.manager_id}}</td> <td>{{ employee.location_id}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> </td> </tr> {% endfor %} </tbody> -
Replace string in .html files with Django custom command
I need to export my django project to static files. I'm using django-distill. Everything works fine except hrefs in main folder directory. So I decided to replace them with custom command after files were generated. However after few attempts I don't know why this function doesn't work. For example if even when I print out soup it show me empty string. class Command(BaseCommand): help='change urls in each header to static version' def replace_urls(self): find_string_1 = 'href="/blog/"' find_string_2 = 'href="/contact/"' replace_string_1 = 'href="blog.html"' replace_string_2 = 'href="/contact.html"' exclude_dirs = ['media', 'static'] for (_, dirs, files) in os.walk(f'{settings.BASE_DIR}/staticpage/'): dirs[:] = [d for d in dirs if d not in exclude_dirs] for filepath in files: f = open(filepath, mode='r', encoding='utf-8') soup = BeautifulSoup(f, "lxml", from_encoding="utf-8") if find_string_1 in soup: soup.replace_with(replace_string_1) if find_string_2 in soup: soup.replace_with(replace_string_2) f.close() def handle(self, *args, **kwargs): try: self.replace_urls() self.stdout.write(self.style.SUCCESS(f'********** Command has been execute without any error **********')) -
Issue with displaying images in frontend
views.py: from PIL import Image img_list =os.listdir(final_path) frontend_images = [] for images in img_list: frontend_path = final_path+str(images) image = Image.open(frontend_path) frontend_images.append(image) print(frontend_images) return render(request,'images.html',{'images':frontend_images}) I am sending the images to the frontend for displaying in frontend images.html {% for img in images %} <img src='{{img}}'/> {% endfor %} Its not displayed in frontend is there other approach to retrieve images from directory and display it in frontend -
Cannot update a field in Django Rest framework
I have to update this 'completed' field in Rest API whenever required. when i go to the url, it is showing a createView but not update view. Also update is not working. How chould i change only 'completed' field to wither True or False whenever i requested a particular Url serializers.py class ToDoModelSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = [ 'content', 'completed', ] models.py class Todo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.content class Meta: ordering = ['timestamp'] views.py class UpdateCompleted(generics.UpdateAPIView): queryset = Todo.objects.all() serializer_class = ToDoModelSerializer permission_classes = (permissions.IsAuthenticated,) def update(self, request, *args, **kwargs): instance = self.get_object() instance.name = request.data.get("completed") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) -
Django - API Post Issue
Im working on a django project and I want to post data to an api. Here is the code: import pandas import requests excel_data_df = pandas.read_excel('workorders.xlsx') json_str = excel_data_df.to_json(orient='records', date_format='iso') // json_str = [{"id":null,"label":"Workorder 1","start":"2019-01-01T00:00:00.000Z","end":"2019-01-10T00:00:00.000Z","duration":9,"ctype":"bar"},{"id":null,"label":"Workorder 10","start":"2019-01-10T00:00:00.000Z","end":"2019-01-14T00:00:00.000Z","duration":4,"ctype":"bar"}] API_ENDPOINT = "http://127.0.0.1:8000/api/chart/data/" API_KEY = "dF8NbXRA.94Mj2xeXT3NZOtx1b575CvNvbs8JWo0D" source_code = json_str data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'csv'} r = requests.post(url = API_ENDPOINT, data = data) I get this error: <h1>Error response</h1> <p>Error code: 405</p> <p>Message: Method Not Allowed.</p> <p>Error code explanation: 405 - Specified method is invalid for this resource.</p> Im using djangorestframework-api-key 1.4.1 to generate the API key. According to the documentation I have to add this to my settings.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } which returns this error: <h1>Error response</h1> <p>Error code: 403</p> <p>Message: Forbidden.</p> <p>Error code explanation: 403 - Request forbidden -- authorization will not help.</p> -
Show ForeignKey in template with class based views
I have a class based DetailView with the model Property as the main model. That model has a foreign key relationship with the model PropertyImage where I store some images. I want to show all related images from PropertyImages in the template detail_view.html together with some details from Property. I know how to do it in a function based view and I tried a lot of things but I failed all the time. Maybe it's just some tiny thing but I don't get it to work. Here is my code: # models.py from django.db import models class Property(models.Model): title = models.CharField(max_length=140, default="Title",) description = models.TextField(max_length=2000) # ... and some more fields def __str__(self): return self.title class PropertyImage(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to='images/') figcaption = models.CharField(max_length=160) def __str__(self): return self.figcaption[:50] # views.py from django.views.generic import DetailView from .models import Property class PropertyDetailView(DetailView): model = Property template_name = 'property_detail.html' For quicker assessment look at the <!-- Here I'm stuck -->section: <!-- property_detail.html --> {% extends 'base.html' %} {% block content %} <div class="container"> <div class="property-entry"> <img src="{{ property.cover_image.url }}" alt="{{ property.title }}" class="img-fluid"> <h2>{{ property.title }}</h2> <p>Description: {{ property.description }}</p> <!-- Here I'm stuck --> {% for image in … -
Django - Keras - Memory stacks-up
I have three deep learning models running on AWS. When there's a call to access models, the memory gets stacked-up with each call without releasing when process ends. At one point, gets out of memory and throws exhaustion error from keras. What am i dealing with? Garbage collector? or the lazy_loader by tensorflow? or something that goes with Django? I have no clue what is happening. Thanks. -
How to have different permission classes for methods in DRF
I have a view similar to this: from django.http import HttpResponse from rest_framework import generics class MyView(generics.ListCreateAPIView): def get_queryset(self): # <view logic> return HttpResponse('result') def post(self, request): # <view logic x2> return HttpResponse('message_post_template') And I would like the GET request to have the permission class of IsAuthenticated and the POST request should have a permission class of HasAPIKey from Django REST Framework API Key. How can I do this? -
django template/views add-to-cart
I have problem, after pressing the 'add cart' button, it expects to add the product and its quantity to OrderProduct and Order. In templates / offers / cart I have no idea how to refer to this quantity and that after selecting it and pressing the 'Add to cart' button it adds the product to cart. Manually, this logic works in the Administrative Panel. offers/views.py def add_to_cart(request, product_id): product = get_object_or_404(Product, product_id=product_id) order_product, created = OrderProduct.objects.get_or_create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # Check if the order item is in the order if order.products.filter(product__product_id=product.product_id).exists(): order_product.quantity += 1 order_product.save() else: order.products.add(order_product) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.products.add(order_product) return redirect("offers:product", product_id=product_id) offers/urls.py urlpatterns = [ path('', views.index, name='products'), path('userproduct', views.userproduct, name='userproduct'), path('<int:product_id>', views.product, name='product'), path('<int:product_id>', views.add_to_cart, name='add-to-cart'), path('cart', views.cart, name='cart'), ] offers/models.py class Product(models.Model): product_name = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.product_name def get_add_to_cart_url(self): return reverse("offers:add-to-cart", kwargs={ 'product_id': self.product_id }) class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) … -
Python input filtered dynamically from another input [duplicate]
This question already has an answer here: How to get Interdependent dropdowns in django using Modelform and jquery? 2 answers I'm working on a Python project using Django. I need to build a form with multiples fields including one depending on another. To help the user, it includes an autocomplete system using autocomplete-light. The problem is the following : I need to filter the content of the second field according to the value of the first one (that the user has already filled). I kinda understand the way of doing it, by sending the value of the first one to the second one, but I don't know how to do it. Does anybody can help me please ? -
Updating one to one model using form in Django
I am very new to Python and Django and am stuck with this problem , which I think should be very simple to solve. model.py class UserDetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) billingAddress = AddressField(related_name='+',blank =True ) # Used django-address https://pypi.org/project/django-address/ shippingAddress = AddressField(related_name='+',blank =True) forms.py class AddressForm(forms.ModelForm): class Meta: model = UserDetails exclude = ['user'] views.py def address(request): form = AddressForm(request.POST or None) if request.method == 'POST' and form.is_valid(): zipCode = request.POST.get("ZipCode","") form = AddressForm(data=request.POST) detailForm = form.save(commit = False) detailForm.user = request.user baddressDict = {'raw':request.POST.get("billingAddress","")+", " + zipCode, 'postal_code': zipCode,} saddressDict = {'raw':request.POST.get("shippingAddress","")+", " + zipCode, 'postal_code': zipCode,} detailForm.billingAddress = baddressDict detailForm.shippingAddress = saddressDict detailForm.save() else: form = AddressForm() return render(request,'showcase/address.html',{'form': form}) What I am trying to do it update the shipping & Billing address for current user. The first time I am doing this it works but the second time it gives UNIQUE constraint failed: showcase_userdetails.user_id which obviously is cause it trying to add another row in the DB. How do i make sure it updates and not insert? Thanks, Gourav -
How to build a python-based auth microservice?
So, what I want to do is to build an app with microservice architecture. I'm going to write all the microservices using Python. I want to build a teaching platform, and I've already known which microservices I'm going to create. So, the application will consist of Teachers, Students, Booking, Notifications microservices. The question is, how to handle authorization with authentication? What I want to do is to create another microservice, which would handle all this auth stuff. But I want to be able to log in just once, and do not type any credentials when I would interact with other microservices. So, there are a few questions I've come up with: How to accomplish a goal of auth microservice, and which free services/libraries I may use for this. I want to handle auth on all my services, but log in just once. What is the most preferable way to write API Gateway? I have a pretty complicated business logic related to registration because students and teachers have a lot of differences. -
how to render django location field by id?
i have a model in django like this : ... class Post (models.Model) title = models.CharField(max_length=120) location = models.PointField(srid=4326, null=True, blank=True) objects = GeoManager() def __unicode__(self): return self.title def get_absoulute_url(self): return reverse("post_map", kwargs={ 'id':self.id }) ... and i want to render location place by id like this: ... path('post-map/<id>/map/',post_map,name='post_map') path('post-map/<id>/index/',home_page,name='post_map') ... an view.py: ... def map (request,id): name = serialize('geojson',get_objects_or_404(Post, id=id) return HttpResponse(name,content_type='json') def home_page(request): return render(request,'home_page.html') ... and home_page.html is: ... <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title> home </title> <style type="text/css"> #gis {width:80%; height:700px;} </style> <script type ="text/javascript" src="{% static 'js2/leaflet.ajax.js' %}" ></script> </head> <body> <h3>we are heroes!!<h3> <br> <script type="text/javascript"> function our_layers(map,options){ var datasets = new L.GeoJSON.AJAX("{% url 'post_map' %}",{ }); datasets.addTo(map); } </script> {% leaflet_map "gis" callback="window.our_layers" %} </body> </html> but i cant render it by id ,is there any way to solve this problem? i can save data and also can render all location to view map functiom with name = serialize('geojson',get_objects_or_404(Post, id=id) but i cant render in by each id for each post is there any way to solve it? -
How to query whole dataset from PostgreSQL using Django models and managers & render frontend with Ajax
I would like to fetch data from a PostgreSQL using Django models/managers and use this data to render my frontend furthermore. I have the following plain simple example where I just get the defined privatekey value in return but not the other information from the table. Estimated outcome: I would like to get all elements of a single row as one object. Models.py: from django.db import models import uuid # Create your models here. class AccountInformationManager(models.Manager): pass class AccountInformation(models.Model): version = models.CharField(max_length=20, blank=False) DID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) accountNumber = models.IntegerField(blank=False) broker = models.CharField(max_length=50, blank=False) leverage = models.CharField(max_length=10, blank=False) account_balance = models.FloatField(max_length=15, blank=False) account_profit = models.FloatField(max_length=15, blank=False) account_equity = models.FloatField(max_length=15, blank=False) account_margin = models.FloatField(max_length=15, blank=False) account_margin_free = models.FloatField(max_length=15, blank=False) account_margin_level = models.FloatField(max_length=15, blank=False) account_currency = models.CharField(max_length=20, blank=False) objects = models.Manager() class Meta: db_table = 'AccountInfo' Query.py: from django.db import models import sys sys.path.insert(0, r"C:\Users\Jonas\Desktop\Dashex") import os os.environ['DJANGO_SETTINGS_MODULE'] = 'Dashex.settings' import django django.setup() from Dashboard.models import AccountInformation //// query data account_information = AccountInformation.objects.all() print(account_information) Printed Output: <QuerySet [<AccountInformation: AccountInformation object (30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f)>, <AccountInformation: AccountInformation object (8b46c7c7-1bc8-4736-8dc5-7d5f012d594b)>]> Process finished with exit code 0 Why it doesn't return the whole data from the table like broker, accountNumberetc.? linked question: Additionally, if I use AJAX …