Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django quill editor | field name displays inside quill editor widget border in Django admin
I am new to Django + Python. I can't really figure out why my field name get displayed inside the Quill Widget in Django admin. It would be great if someone who already figured out this problem share their solution. Django==3.2.4 | django-quill-editor==0.1.22 My code: # models.py class Post(models.Model): post = QuillField("Post", null=True, blank=True) # admin.py @admin.register(Title) class TitleAdmin(admin.ModelAdmin): pass image of the problem - Sorry, I don't have enough reputation to embed an image. Many thanks, -
Please how can I resolve this error :"NoReverseMatch at /projects/?"
In my Django project, if i click on projects ,I will be getting NoReverseMatch Error[Error code -
Pass urls iteratively into django html template url tag
I have a home template with links to many other pages which I want to render iteratively: (this obviously does not work due to python syntax) {% for idx, category in enumerate(categories) %} <div class="box"> a href={% url 'category_links[idx]' %}> {{category}}</a> div> {% endfor %} I have the following urls which I also pass to my template from my view: category_links = ['journals', 'proceedings', 'books', 'articles_in_books', 'talks', 'poster', 'habilitations', 'phd_thesis', 'bachelor_master_diploma_thesis', 'lectures', 'conferences', 'calls_and_awards', 'telegrams_and_circulars'] I am aware of {{forloop.counter0}} but was unable to integrate it properly. I would greatly appreciate some help! -
Converting HTML to PPTX using Python
Is there a way to convert at least HTML text styling to PPTX? I'm using Django for an website, and I want to be able to export a page to PPTX. I tried using python-pptx, and I was able to inject the raw text into a PPTX template, but I also want to keep the text formatting (colors, font size), and ideally the slide would look exactly the same as the HTML website. -
Gitlab ci fails to run docker-compose for django app
I am setting up a gitlab pipeline that I want to use to deploy a Django app on AWS using Terraform. At the moment I am just setting up the pipeline so that validates the terraform and runs tests (pytest) and lynting. The pipeline uses docker in docker and it looks like this: image: name: hashicorp/terraform:1.0.5 entrypoint: - '/usr/bin/env' - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' stages: - Test and Lint Test and Lint: image: docker:20.10.9 services: - docker:20.10.9-dind stage: Test and Lint script: - apk add --update docker-compose - apk add python3 - apk add py3-pip - docker-compose run --rm app sh -c "pytest && flake8" rules: - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^(master|production)$/ || $CI_COMMIT_BRANCH =~ /^(master|production)$/' The pipeline fails to run the tests due to a database error I think which is weird as I am using pytest to mock the django database. If I just run: docker-compose run --rm app sh -c "pytest && flake8" on the terminal of my local machine all tests pass. Any idea how can I debug this? p.s. let me know if I need to add more info. -
Django recurring record/payment calculation
I have a table of "expected payments" that either are a one-time payment, or recurring monthly, quarterly or yearly. The goal is to calculate the total amount of expected payments for each of the upcoming 12 months. The model looks like: class ExpectedPayment(models.Model): id = models.BigIntegerField(primary_key=True) period = models.BigIntegerField() date_start = models.DateField(blank=True, null=True) date_end = models.DateField(blank=True, null=True) amount = models.DecimalField(max_digits=1000, decimal_places=1000) Period 1 = Monthly recurring Period 2 = Every Quarter - Following the start date. (So started on February, next quarter is May) Period 3 = Yearly recurring - Also following the start date Period 4 = One time payment How can I properly calculate the total "amount" for each month, while taking into account when a payment should take place? Especially the quarterly payments.. I can't figure out how to incorporate when a payment has been started and ended, as it might have been started halfway throughout the year, ended 3 months later or was already finished in the first place. How do I know which month the quarterly should count as an expected payment, when it is always relative to its start_date. An example for a single month: (every monthly payment that is active in the current … -
How to add students to class in by teacher in one click in Django rest framework
I have models named Student and Teacher. Teacher will be able to see all the students through get api (students name). Now the requirement is, by just clicking one button on the side of the list of student name, teacher should be able to add the student to his class. How to associate students to teacher in this cases. Because same students can be added to other class by other teacher as well. class Student(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="student", on_delete=models.CASCADE) college_name = models.CharField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name class Teacher(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="teacher", on_delete=models.CASCADE) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name -
Django with reportlab pdf
The following code works and prints pdf as required, but everything prints on single page only, how I can automatically generate new pages when data builds up, seeking an advice def pdf_view(request): buf = io.BytesIO() c = canvas.Canvas(buf) c.setPageSize(landscape(A4)) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) rows = [] users = User.objects.filter(is_staff=False) for user in users: rows.append(( user.username, user.email, user.first_name, user.last_name, )) table = Table(rows, colWidths=46 * mm) table.setStyle([ ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 0), (-1, -1), "LEFT"), ]) table.wrapOn(c, width, height) table.drawOn(c, 10 * mm, 10 * mm) styles = getSampleStyleSheet() ptext = "Member List" custom_style = ParagraphStyle( "Normal", fontName="Helvetica-Bold", fontSize=16, parent=styles['Heading2'], alignment=1, spaceAfter=14 ) p = Paragraph(ptext, custom_style) p.wrapOn(c, 100 * mm, 100 * mm) p.drawOn(c, 100 * mm, 195 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='members.pdf') -
django model formset how to make formset from two tables(or with one to one field)
I would like to make page to verify users, simple page, just username and checkbox near. what i getting how look it now id like make ModelChoiceField look like simple username text, or ModelChoiceField disabled. My code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='id пользователя', related_name='model') phone = models.CharField(max_length=30, verbose_name='Номер телефона', blank=True) city = models.CharField(max_length=36, blank=True, verbose_name='Город') is_verified = models.BooleanField(default=False, verbose_name='Проверен') published_news = models.IntegerField(default=0, verbose_name='Количество опубликованных новостей') class UserVerifyView(View): def get(self, request): template_name = 'app_users/verify.html' formset = UserVerifyFormSet() context = {'title': 'Верификация', 'formset': formset} return render(request, template_name, context) {% block content %} <div class="container"> {% csrf_token %} {{ foromset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} </div> {% endblock %} -
How to unittest test Django ModelForms with kwargs
I am trying to write unit tests for a Django ModelForm. This form's init method has been overridden so as to access the current user in the kwargs variable. However, anytime I run the test, it always brings this error form = UserCreationForm(data={'email': 'test@email.com', File "C:\Users\CODING\django\project1\bookapp\forms.py", line 45, in __init__ self.current_user = kwargs.pop('current_user') KeyError: 'current_user' views.py @method_decorator([login_required], name='dispatch') # Only logged in users can access the page class BookCreateView(CreateView): template_name = "new_book.html" model = Book def get_form_kwargs(self): kwargs = super(BookCreateView, self).get_form_kwargs() kwargs['current_user'] = self.request.user return kwargs forms.py class BookCreationForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'isbn', 'author') def __init__(self, *args, **kwargs): self.current_user = kwargs.pop('current_user') # Line 45 super().__init__(*args, **kwargs) # Some removed code tests def test_save(self): new_user = get_user_model().objects.create_user( email='test1@email.com', password='secret', first_name='John', last_name='Doe', ) user = get_user_model().objects.get(id=1) # This tests the save method form = BookCreationForm(data={'email': 'test@email.com', 'first_name': 'John', 'last_name': 'Doe', 'current_user': user, }) book = form.save() Anytime I run the test, it fails because of that KeyError -
How is this pluralize not working on Django template?
Was working on Django, following the documentation I got stuck at this point, for some reason pluralize isn't working well on my template where I specified it. Ask if more part of code is required. Consider telling what's wrong in here??? Views Output screen -
Django two websites hosted with Apache, urls do not work at one of them
I did set up two websites (hosted locally). I'm on windows so config may look odd. WSGIPythonHome "C:/var/www/magazyn/env39" WSGIPythonPath "C:/var/www/magazyn/venv/Lib/site-packages;C:/var/www/magazyn/rootkat/" ServerName www.magazyn-stolarz.pl LoadFile "C:/Python39/python39.dll" LoadModule wsgi_module "C:/var/www/magazyn/env39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIScriptAlias /awizacje "C:/var/www2/awizacje/rootkat/awizacje/wsgi.py" WSGIScriptAlias / "C:/var/www/magazyn/rootkat/magazyn/wsgi.py" <Directory "C:/var/www2/awizacje/rootkat/awizacje/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /statica "C:/var/www2/static/" <Directory "C:/var/www2/static/"> Require all granted </Directory> <Directory "C:/var/www/magazyn/rootkat/magazyn/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/var/www/static/" <Directory "C:/var/www/static/"> Require all granted </Directory> With that configuration base site works perfectly ("pc-name/") but the second one ("pc-name/awizacje") does not. Main url works like it should but every button sends me to ("pc-name/button-url") and not ("pc-name/awizacje/button-url"). I have set ROOT_URLCONF = 'awizacje.urls' in settings.py. Is there something I am missing? Any way I should change settings to take base url into account? -
Django - Join two Table without Foreign key
I have two tables and want to join them.. but I can't do that without rawQueryset. how can i join two models without foreign key? The column for JOIN is not unique so it can't be PK and Foreign Key. I want to get the SQL LIKE THIS 'SELECT * FROM genome AS A JOIN metadata AS B ON A.query_id = B.sample_id', and this the models I used. class Genome(models.Model): query_id = models.CharField(max_length=100) ref_id = models.CharField(max_length=30) matching_hashes = models.CharField(max_length=30) class Metadata(models.Model): project_id = models.CharField(max_length=50) # Metagenome의 query id와 JOIN함 sample_id = models.CharField(max_length=50) -
Cannot connect to redis in docker and django
I have run a redis container using this command: docker run -d --name redis -p 6379:6379 redis. and I have run my Django app using this command: docker run -it -p 8000:8000 voucher. and my connection redis url is redis://redis:6379/1. But i cannot seem to connect to redis here is my error: redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known. -
Django problem with missing " underscore" in url
I am a beginner and need a little support. Everything works in the application, but when in the form it typing "new york", "_" is missing in the url. My code is res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=1b79ea7b1251b7a830b41a81d6bd').read() In response receives " InvalidURL at / URL can't contain control characters. '/data/2.5/weather?q=bielsko biala&appid=1b79ea7b1251b76cc0b41a81d6bd' (found at least ' ') I am looking for solutions on the Internet but I cannot solve it myself. Thank you very much for all your help -
django admin page links broken and always redirect to the home page(/admin)
We are running django with gunicorn + Nginx on amazon ecs with docker. For authentication and as SSO(single sign-on) provider, we are using Auth0. The admin page links have been working fine for some time but they suddenly stopped working in our dev environment. All of the links in the admin page redirect back to the admin homepage i.e if you click on the User model to see the users you just get redirected back to the admin homepage. We have tried so many solutions and it has been a very bizarre bug for us. The main reason this error is so confusing is that we have the same exact code with similar configurations on our staging environment and all the admin page links work perfectly in it. To enable authentication and SSO with Auth0 we are using a python library called python-social-auth and we think the problem could be caused maybe by a cookie or redirect-related issue coming from it. so we tried different configurations for it per the documentation and some StackOverflow answer to questions similar to this one but to no avail. This is our current settings.py configuration: # Auth0 Authentication Related Configs Keys SOCIAL_AUTH_PROTECTED_USER_FIELDS = [ … -
an error occured when TensorRT engine reference runs under the Django framework
I use the transformed tensorrt engine for a BertTokenClassification model referenceing in Django service, the following errors occur: [TensorRT] ERROR: 2: [pluginV2DynamicExtRunner.cpp::execute::115] Error Code 2: Internal Error (Assertion status == kSTATUS_SUCCESS failed.) This error is located in this line: context.execute_async_v2(bindings=bindings[:4] + [bindings[4]], stream_handle=stream.handle) However, it is puzzling that if the same reasoning code is not run in the Django service, no error occures. Could you help me what is the cause of this problem? -
Am I passing user object to ModelForm using CreateView correctly?
I'm developing a booking portal that allows a logged in user to create a delivery slot (booking). models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField() delivery_time = models.TimeField() booking_number = models.CharField(max_length=50,null=False) # def save(self, **kwargs): # if not self.booking_number: # self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" # super().save(**kwargs) def get_absolute_url(self): return reverse("booking_detail",kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking from bootstrap_datepicker_plus import DatePickerInput import datetime as dt HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('qty_plts','cbm','delivery_date','delivery_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6]}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} views.py from django.shortcuts import render # Create your views here. from .models import Booking from django.urls import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (ListView,DetailView,CreateView,UpdateView,DeleteView,TemplateView) class AboutView(TemplateView): template_name = 'about.html' class BookingCreate(LoginRequiredMixin,CreateView): login_url = '/login' redirect_field_name = 'bookmyslot/booking_detail.html' model = Booking form_class = BookingForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.user.booking_number = f"{self.request.user.delivery_date:%Y%m%d}{self.request.user.delivery_time:%H%M}" self.object.save() return super().form_valid(form) I want the booking number to be generated at the time of form creation, for the … -
file upload and process in django
I am a django beginner and here is what I am trying to build. upload a file using django form in media_root read the uploaded file by calling a function from my data extraction python file upload extracted data to databse using django models. Appreciate if experts can provide an example for what I am building. Thanks, Sam -
Combining Django DateField and TimeField in ExpressionWrapper gives TypeError: expected string or bytes-like object
I have a Request model that has a Foreign Key to a Slot My Slot models look like this:- class Slot(models.Model): day = models.DateField() start_time = models.TimeField() end_time = models.TimeField() In my views, im trying to annotate the day and start_time fields to compare them with the current time, from django.db.models import DateTimeField, DateField, TimeField, ExpressionWrapper, F pending_requests = Request.objects.annotate( my_dt=ExpressionWrapper( F('slot__day') + F('slot__start_time'), output_field=DateField() ) )[0] This gives me: TypeError: expected string or bytes-like object When I annotate each field to its respective field type, it works fine, pending_requests = Request.objects.annotate( my_dt=ExpressionWrapper( F('slot__day'), output_field=DateField() ) )[0] Not sure if Im combining the fields correctly or how I can fix this please -
Django - use raw query and order by with parameter
data_list = Data.objects.raw( 'SELECT * FROM data_table ORDER BY %(order_col_name)s', {"order_col_name" : order_col_name}) I use this code but..Ordering doesn't work. I think the raw function cann't pass the ordering column parameter. Can anybody help? -
Django formset for all choices in a given model field with prefilled values for the Choice Field
I have a model as follows: AGE_GROUPS = ( ('<1', '<1'), ('1-4', '1-4'), ('5-9', '5-9'), ('10-14', '10-14'), ('15-19', '15-19'), ('20-24', '20-24'), ('25-29', '25-29'), ('30-34', '30-34'), ('35-39', '35-39'), ('40-44', '40-44'), ('45-49', '45-49'), ('50+', '50+'), ) class Data(models.Model): dataset = models.ForeignKey('data.Dataset', on_delete=models.CASCADE) indicator = models.ForeignKey('data.Indicator', on_delete=models.CASCADE) facility = models.CharField(max_length=120, choices=FACILITIES) month = models.CharField(max_length=20) age_group = models.CharField(max_length=10, choices=AGE_GROUPS) male = models.PositiveIntegerField(blank=True, null=True) female = models.PositiveIntegerField(blank=True, null=True) And a form and formset as follows: class DataForm(forms.ModelForm): class Meta: model = Data fields = ['age_group', 'male', 'female'] DataFormset = forms.modelformset_factory(Data, form=DataForm, extra=len(AGE_GROUPS)) And this is the problem: In the template, I want the formset to be rendered as a table for all the age groups with the Age groups prefilled. Better still, is there a way to have the Age Group as a non-editable column, but the male and female editable? Mind you if the particular record already has values (for male and female), then the respective formset row should be prefilled as well. Here's my view so far: def home(request): data_formset = DataFormset(request.POST or None) # -> The below code is not working when the model has existing data # (I'm open to any approach) # Prefill the Age Groups in the formset # … -
python use case with django and other libraries and have to answer the following questions with it
I am completely new to python and had this university use case in the assignment. Need help with it. your help will be highly appreciated in advance. Kindly help me with this problem. import os import django import datetime from pytz import timezone from xwing import settings from gentella.api_access.emarsys.api import EmarsysApi from collections import namedtuple from typing import List os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xwing.settings") django.setup() from gentella.emarsys_models.models import ContactSegment brand_shop_segment = namedtuple('brand_shop_segment', ['id', 'name', 'count', 'brand']) def get_segment_info_as_df(brand: str) -> List[brand_shop_segment]: assert brand in settings.EMARSYS_LOGINS.keys(), 'passed \'brand\' is not in EMARSYS LOGINS' etc_timezone = timezone('Europe/Amsterdam') api = EmarsysApi(username=settings.EMARSYS_LOGINS[brand]['username'], secret_token=settings.EMARSYS_LOGINS[brand]['secret'], tzinfo_obj=etc_timezone) segment_data = api.get_segments() segments = [] for segment in segment_data: segment_count = api.get_segment_contact_count(segment_tuple=segment) brand_segment_combo = brand_shop_segment(id=segment_count.id, name=segment_count.name, count=segment_count.count, brand=brand) segments.append(brand_segment_combo) return segments def save_segments(segment_info: List[brand_shop_segment], brand: str) -> None: today = datetime.datetime.today().date() ContactSegment.objects.filter(dt=today, brand=brand).delete() data_list = [] for segment in segment_info: data = ContactSegment( id=segment.id, name=segment.name, count=segment.count, brand=segment.brand, dt=today ) data_list.append(data) ContactSegment.objects.bulk_create(data_list) def main() -> None: for brand in settings.EMARSYS_LOGINS.keys(): print(brand) segment_list = get_segment_info_as_df(brand=brand) save_segments(segment_list, brand=brand) if _name_ == '_main_': main() ============================================================================================== Questions: What type of process is the code supporting? Kindly walk us through the code – main functions, objects, general functionality. What is exactly the purpose of line 19? Could the … -
Django Query set: Duration from two DateTimeField()
In my Django project, I have a model like this- class Task(models.Model): ticket_number = models.CharField() order_number = models.CharField() number_of_errors = models.IntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField() I'd like to make a query set "tasks" where I'll include working_date, ticket_number, order_number, and work_hours(end_time-start_time) in HH:MM:SS for example 03:55:01 format. "working_date" will be derived from end_time. Once I get the query set right, I'll export the result in a CSV. I can do the query in MySQL like this: SELECT DATE(end_time) AS working_date, ticket_number, order_number, TIME_FORMAT((TIMEDIFF(end_time,start_time)),'%H:%i:%s') AS work_hours FROM task WHERE end_time>= pStartDate AND end_time< pEndDate; How do I do this in Django ORM? -
TemplateDoesNotExist at / templates/home/hom_page.html
i'm using django here's my views code: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'templates/Home/Home_page.html') here's my urls code: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), ] here's img: