Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add sound player to django admin panel
I have model with FileField, which contains audio file: class Word(models.Model): theme = models.ManyToManyField(Theme, related_name='words') name = models.CharField(max_length=200, null=True, blank=True) sound = models.FileField(upload_to='sounds/', blank=True) I need show audio player on admin panel for this model. For example, for ImageField I did this: from django.utils.html import mark_safe and add property to model code @property def icon_preview(self): if self.icon: return mark_safe(f'<img src="{self.icon.url}" width="100" height="100" />') return "" in admin.py add code: list_display = ('id', 'name', 'icon', 'icon_preview') readonly_fields = ('icon_preview',) def icon_preview(self, item): return item.icon_preview icon_preview.short_description = 'icon preview' icon_preview.allow_tags = True And I need to do something similar for the sound -
ModuleNotFoundError at / when django heroku host
[i can't integrate my Django project, it says ModuleNotFoundError at / ]1 -
How to view relational data in both snippets in Django Wagtail?
I have define two models "A" and "B" in Django Wagtail. Model "A" has many to many relation with "B" in it's model. I use wagtail snippets to edit them in Admin panel. Is it posible to view both relational data in each admin snippets? If so I wanted to restrict the edit feature in model "A" -
Django Insert Data into database via php
For now I always created the structure and logic of my backend with Django. But when I insert data into the database I alwas did that directly via a http request to a php script. When the projects grows it is getting pretty messy. As well, there were always complications with timestamps from the database to the backend. I want to eliminate all these flaws but could not find any good example If I could just make a request to a certain view in Django, containing all the information I want to put into the database. Django and the database are on the same machine, but the data that is being inserted comes from different devices. Maybe you could give me a hint how to search further for this -
Django display data from two different models
I have two seperated models. One with two text fields and one for multiple images. Now I want to display the entire data in one html div. What do I have to change in the projects view and in projects.html? Thanks models.py class Project(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) class ProjectImage(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) image = models.FileField(upload_to="products/") forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['title', 'describtion'] class ProjectImageForm(forms.ModelForm): class Meta: model = ProjectImage fields = ['image'] widgets = { 'image': ClearableFileInput(attrs={'multiple': True}), } views.py def createProject(request): form = ProjectForm() form2 = ProjectImageForm() if request.method == 'POST': form = ProjectForm(request.POST) form2 = ProjectImageForm(request.POST, request.FILES) images = request.FILES.getlist('image') if form.is_valid() and form2.is_valid(): title = form.cleaned_data['title'] describ = form.cleaned_data['describtion'] project_instance = Project.objects.create( title=title, describtion=describ) for i in images: ProjectImage.objects.create(project=project_instance, image=i) context = {'form': form, 'form2': form2} return render(request, 'projects/project_form.html', context) def projects(request): projects = Project.objects.all() context = {"projects":projects} return render(request, 'projects/projects.html', context) projects.html {% for project in projects %} <div class="column"> <div class="card project"> <img class="project__thumbnail" src="{{project.image.url}}" alt="project thumbnail" /> <div class="card__body"> <h3>{{project.title}}</h3> <h2>{{project.describtion}}</h2> </div> </a> </div> </div> {% endfor %} -
How to convert html to pdf in django?
I'm starting with Django and I working with HTML and I would like to convert to pdf. I have this view wich I get the data registered in my DB by id: def contrato(request, id): return render(request,'contrato\contrato.html', {'asociado': get_queryset(id)}) This renders me the following html, it is something simple: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CPS</title> </head> <body> <h1>Contrato de Prestación de Servicios</h1> <div> <ul> {% for dato in asociado %} <li>Función/Título: {{ dato.job_title }}</li> <li>nombre completo: {{ dato.first_name }} {{ dato.last_name }}</li> <li>Email: {{ dato.email }}</li> <li>RFC: {{ dato.rfc }}</li> <li>CURP: {{ dato.curp }}</li> <li>Clabe: {{ dato.interbank_key }}</li> <li>País: {{ dato.country }}</li> <li>Status: {{ dato.status }}</li> <li>Creado: {{dato.created}}</li> {% endfor %} </ul> </div> </body> </html> How can I convert this html to pdf with the registered data to download. I have only achieved an empty pdf (without the data) or only with the H1 header. I will appreciate any help! -
How can i attach django models data as Excel file and send it as mail with SMTP
i have some data in django models and i want to make excel file from that data and attach it in SMTP as file and send it to target user. i am also using django-import-export to export the excel files .but in this case i want to attach the file in email. Model class FinalBill(models.Model): shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False) customerReference = models.CharField(max_length = 200, blank = True, null = True) customerConfirmation = models.CharField(max_length = 200, blank = True, null = True) deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True) address = models.CharField(max_length = 200, blank = True, null = True) service = models.CharField(max_length = 200, blank = True, null = True) weight = models.FloatField(blank = True, null = True) pricingZone = models.CharField(max_length = 200, blank = True, null = True) uspsCompRate = models.FloatField(blank = True, null = True) charges = models.FloatField(blank = True, null = True) surcharges = models.FloatField(blank = True, null = True) totalSavings = models.FloatField(blank = True, null = True) totalCharges = models.FloatField(blank = True, null = True) customerID = models.CharField(max_length = 200) is_exported = models.BooleanField(default=False) exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False) def __str__(self): return … -
Exception Value: no such column: blog_app_article.slug in django
I have a problem with slug. my code is running well but just when I add slug=models.SlugField(default=True,max_length=40) to my model. it stops and give me the error : OperationalError at / no such column: blog_app_article.slug when I delete the slug, my code run well again. I've deleted database and make it again but it doesnt work. what's the problem? I'm coding on Pycharm 2020.1.3 and Django 4.0.4 -
How do I create a group as well as add members to it to make a queryset for Postman?
class AddUserToGroupApiView(APIView): """ Create a hello message with our name """ def post(self, request): serializer = GroupSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data group = Group.objects.create(group_name=data.get('group_name')) print(group) group_name = request.data.get('group_name') members = request.data.get('members') print(members) print(group_name) user = UserProfile.objects.filter(name=members) print(user) groups = Group.objects.get(group_name=group_name) print(groups) if not groups.members.filter(members=user).exists(): groups.members.add(user.email) return Response({"status": "Group Created"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can add users to the created group and make a group_name , members query in Postman? -
name 'c' is not defined in python
I tried to make a calculator with Django, but got this error this view function takes the input from html page and do the calculation where is the problem here? views.py - from django.shortcuts import render from django.template import loader from django.http import HttpResponse # Create your views here. def indx(request): template = loader.get_template('calculator/calc_home.html') if request.method=='POST': global c,a,b a=request.POST.get('num1') b=request.POST.get('num2') option=request.POST.get('select_val') if a=="" or b=="" : c='please select 2 numbers' else: if option=='add': c=int(a)+int(b) elif option=='multiply': c=int(a)*int(b) elif option=='substract': c=int(a)-int(b) elif option=='devide': if int(b)+0== 0: c='infinity' else: c=int(a)/int(b) else: c='please choose an option' context={ 'sum':c } return HttpResponse(template.render(context,request)) calc_home.html html code takes the input and passes it to the view <h1>welcome to calculator</h1> <p>enter 2 numbers</p> <form method="POST"> {% csrf_token %} <label for="num_1">enter 1st number:</label> <input type="number" name="num1" value='num_1'><br> <label for="num_2">enter 2nd number:</label> <input type="number" name="num2" value='num_2' ><br> <input type="radio" value="add" name="select_val" id="add" > <label for ="add">+</label><br> <input type="radio" value="substract" name="select_val" id="subs" > <label for ="subs">-</label><br> <input type="radio" value="multiply" name="select_val" id="multiply" > <label for ="multiply">*</label><br> <input type="radio" value="devide" name="select_val" id="devide" > <label for ="devide">/</label><br> <input type="submit" name="submit" value="submit"> </form> <h1>{{ sum }}</h1> <br><a href="{% url 'home:homex' %}">go to home</a> error this error is coming in the html page name 'c' … -
Module not found: Error: Can't resolve '@popperjs/core' in 'C:\Users\jkids\mit-tab\node_modules\bootstrap\dist\js'
I'm trying to do a python devserver and keep getting this error, it's running with MySQL and Django; I've tried npm installing @poppyjs/core and poppy.js and neither work -
Linked the css file in django html template but no output
I linked my django html template with the css file, but there is no error and no changes in the page. And when I write the same css code in the same html file under the tag, it works correctly, can someone please guide on what is going wrong? Attaching the code of html file and settings file. HTML File <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>TPC - Student Dashboard</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ color: white; opacity: 1; /* Firefox */ } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: white; } ::-ms-input-placeholder { /* Microsoft Edge */ color: white; } *{ background:#E7E9F0; font-family: "Segoe UI", Arial, sans-serif; } </style> <link rel='stylesheet' src="{% static 'Dashboards/student_dashboard.css' %}"> </head> <body> </body> </html> settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = DEBUG = TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'loginRegistration', 'dashboards', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tpcAutomation.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, … -
How to change the behaiour of django_spanner application on entire djano project? As I am using 2 databases inside my django application
My Django application has 2 databases (spanner and AWS RDS). I am trying to integrate spanner DB with existing RDS (following the Django spanner document mentioned at the link below). It says we should include the django_spanner application inside the INSTALLED_APPS list. I have multiple applications inside my Django project but I want to use spanner only for one app. After following the steps that are mentioned in the below document, it says The django_spanner application changes the default behavior of Django's AutoField so that it generates random values (instead of automatically incrementing sequentially). This seems to be done to avoid a common anti-pattern in Cloud Spanner usage. I don't want this to happen for other tables where auto-generated id keys are getting randomly generated after including django_spanner, because the other tables will still be in AWS RDS(where we need automatically increasing ids). Can anyone please suggest any solution? https://cloud.google.com/blog/topics/developers-practitioners/introducing-django-cloud-spanner-databas -
how to instance and update multiple row in a table with Django
I have a simple table with some rows: My goal is to instantiate the current value of the quantity and eventually save the new data for all the lines. At the moment I have a simple view: @login_required def compilaDocMultiRow(request,pk): member = get_object_or_404(testaDoc, pk=pk) family = corpoDoc.objects.filter(doc=pk) if request.method == "POST": form = multiCorpoDocForm(request.POST or None) if form.is_valid(): reg = form.save(commit=False) reg.doc_id = member.pk reg.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: print(form.errors) else: form = multiCorpoDocForm() return render(request, "compilaDocMultiRow.html", {'family':family, 'member':member, 'form':form}) Is there a way to do this using only Django? -
One to Many field in Model of Django
I am creating a model in Django, but quite confuse about the type of field should i take: Problem: I have to access multiple domains in one web classification, advice me please how do i make these field relationship so that if I try to get one web classification details then it will also contain list of related domain in that as well. Model.py: class WebClassification(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) domain_name = models.[what type i take here] def __str__(self): return self.name Domain.py class Domain(models.Model): id = models.IntegerField() domain_name = models.CharField(max_length=200) def __str__(self): return self.domain_name -
How to create a url for two apps that have index function in django?
I am a newbie in Django. In one django project, I have two apps say college app and company app. In the college app, I have in the college\urls.py path('', index, name="index") and in another company app, I have path('company/', HomeView.as_view(), name="index"). How do I create a url of both these in the header.html ? I tried these but its not working College Home Page ||` Company Home Page || -
print out celery settings for django project?
I'd like to know if celery settings specified in the settings.py file is actually being recognized. How can I tell if celery picked up the options? -
Two .css file in Django static folder only one can be found
I can't understand as the title described. Please refer to image below: The two css files is under the same folder and in the template file I copy the link line just changed the file name. Why the abc.css file can't be found as shown in the command line screen? I just can't understand. Also anther image file is also not found either, also a mystery to me. -
DeleteView lead to error 405 when submit is clicked on django
I have this small blog post where everything works fine apart from delete view. As soon as I hit confirm from DeleteView html page I get 405 error my views.py looks like this my html file where the link is mentioned is like this urls looks this way and html for deleteview -
Django celery unregistered task
I'm running two django projects in one VM and for that two separate celery process is running with supervisor. Now suddenly the tasks is getting clashed with other process. I'm getting unregistered task error. I don't know how of sudden i'm facing this issue. Earlier it was working and nothing changed in the configurations. The above attached image is a reference and task is registered in other service but how of a sudden it's running here. I tried so many solution not able to find the root cause. Any help is appreciated. -
(Django) Сменил директорию проекта, перестали работать команды в терминале
Перекинул папку проекта в другую, вродь как указал путь интерпретатора, но все равно не могу выполнить командуenter image description here -
Automating Celery monitoring for abnormal queue length
I'm using Django/Celery/Redis to handle tasks that import large amounts of data into my db. Occasionally, something will go wrong and the workers seemingly hang -- I'm curious if there's a way for me to monitor the size of my queues inside of my Django application so that I can create a custom alert. For example, if my queue grows above 100, I'd like to create an alert. Right now, I'm just periodically checking the queues via the Redis CLI, but that is not sustainable. I realize that this question may be vague since there's no code, but I'm just not sure where to start here. -
Add a new attribute in serializer but doesn't appear
I want to add a new attribute apartment_sold in the Transaction serializer, but I seem it doesn't work! serializes.py class TransactionSerializer(serializers.HyperlinkedModelSerializer): buyer = serializers.ReadOnlyField(source='buyer.username') apartment_sold = serializers.HyperlinkedRelatedField(view_name='sold-detail', read_only=True) class Meta: model = Transaction fields = [ 'id','buyer','apartment_sold','timestamp' ] views.py class SoldViewSet(viewsets.ReadOnlyModelViewSet): queryset = Apartment.objects.filter(issold=True).order_by('-timestamp') serializer_class = ApartmentSerializer class TransactionViewset(viewsets.ModelViewSet): queryset = Transaction.objects.all().order_by('-timestamp') serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): transaction = serializer.save(buyer=self.request.user) transaction.apartment.issold = True transaction.apartment.save() -
how to add if condition in django with compare session value in html
I have an error when I compare the value of the session in the HTML templates error: Could not parse the remainder: '{{' from '{{' {% if {{ request.session.userinput }} == "Too low!" and {{ request.session.attempt }} < 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{request.session.userinput}}!</h1> </div> {% elif {{request.session.userinput }} == "Too high!" and {{request.session.attempt}}< 5 %} <div class="box" style="background-color:rgb(235, 66, 66);"> <h1 class="boxh1">{{ request.session.userinput }}!</h1> </div> {% elif {{ request.session.userinput }} == {{ request.session.number }} and {{request.session.attempt}} < 5 %} <div class="box" style="background-color: rgb(119, 245, 147);"> <h1 class="boxh1">{{ request.session.number }} was the number!</h1> <a href="/destroy_session"><button class="replay-btn">Play again!</button></a> </div> {% endif %} <div id="k" class="form" > <form action="/guess" method="post"> <input class="num" type="text" name="num" required value=""/><br> <input class="btn" type="submit" value="Submit" /> </form> </div> view.py def guess(request): if request.session["attempt"]==5: request.session["attempt"]=5 if request.session["number"] == int(request.POST["num"]): request.session["userinput"] =request.session["number"] elif request.session["number"] < int(request.POST["num"]): request.session["userinput"]="Too high!" request.session["attempt"] += 1 elif request.session["number"] > int(request.POST["num"]): request.session["userinput"]="Too low!" request.session["attempt"] += 1 context ={ "attempt":request.session["attempt"], "userinput":request.session["userinput"], "number":request.session["number"] } return render(request,'index.html',context) Is correct the way that I compare session values in HTML? -
Confused about the import syntax in django for Render()
Im trying to understand the period in from django.shortcuts import render Does it mean from the django directory in the shortcuts file? Or does it mean from the django directory, from the shortcuts directory, import the render file?