Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid parameters after copying a plugin in Dajngi CMS
I'm coding a website in Django CMS and I have a few plugins added. However, when I copy a plugin copying plugin and switch to another language via toolbar on top toolbar (either the current language or any other that was defined in settings.py file), I have the following error: error Does anyone know how to resolve the error? I have no idea why it is happening. However, the plugin was copied and if I go back to the home page (http://127.0.0.1:8000/en/) and choose a language again, then paste my plugin in, it will be inserted paste in. -
custom login with windows authentication in django
I got a custom user login using my own database to enter a web I created. The question is if is it possible to verifiy the user login with widnows authemtication, I appreciate your responses, thanks I search for login with windows auth and I only found login auth for admin page -
Is there a way to start huey with django and pass settings only related to huey?
When I start huey with manage.py it brings all the settings and logic from the current configuration class. Is there a way to pass only huey-related settings to huey? Something like python manage.py run_huey --configuration=HueyConfiguration Thanks. -
regex for finding a keyword from a sentence in python
I have written a piece of code for detecting if a keyword exists in a sentence. Following is my regex: re.search(r'\s'+keyword+r'\s', message, re.IGNORECASE)** There are following cases for which I want my regex to work: Let's take an example where keyword is hello we want this regex to work if the message is hello, my name is tia. i.e. the keyword comes in the beginning. it should also work, if the keyword comes in the end of the message like. my name is tia, hello. even if it comes in the middle, this should work fine like if the message is i am tia. hello. i love python. if there is a new line before or after our keyword, we expect the regex to work. i am tia. hello i love python. NOTE: it should only return true if there exists the whole keyword inside the sentence and not just a substring of the keyword. re.search(r'\s'+keyword+r'\s', message, re.IGNORECASE)** i have tried the above regex but it doesn't really seem to work. -
An editable table or form in Django (table like Excel) is online editable
Good day! I have a table model in Django . I am displaying the last 10 rows from this model in a simple table on the app. I really need to change this data in some kind of interface in a Django application. 10 table rows from the model. I'm looking for options as possible when clicking on a cell to make it possible to edit its contents. Just like in Excel spreadsheets. And at the end, click on the button and send the edited part to the Django internal part, to the model. I wanted to ask if anyone has such information on how to do something like this? I would be very grateful for any information. -
Optimize DjANGO's ORM
I am trying to display the post and all the comments of this post. Comments have likes, so their number also needs to be displayed. But it is not possible to optimize these queries. The problem is that django turns to vi every time to get author and quotes_comment_like from there to count the number of authors who have put likes. Models.py class QuotesHonors(models.Model): quotes = models.TextField() liked = models.ManyToManyField(Profile, related_name='likes_quotes', blank=True) editor = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, related_name='quotes_editor') author = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, related_name='quotes_author') category = models.ManyToManyField( 'Category', related_name='quotes_category') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def number_comments(self): return self.quotes_comment.all().count() class Like(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_like') quotes = models.ForeignKey(QuotesHonors, on_delete=models.CASCADE, related_name='quotes_like') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f'"{self.user}" like "{self.quotes}"' class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comment') quotes = models.ForeignKey(QuotesHonors, on_delete=models.CASCADE, related_name='quotes_comment') body = models.TextField(max_length=300) liked = models.ManyToManyField(Profile, related_name='likes_comment', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def number_likes(self): return self.liked.all().count() def __str__(self) -> str: return f'"{self.user}" comment "{self.quotes}"' class CommentLike(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comment_like') comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='comment_like') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f'"{self.user}" like comment "{self.comment}"' Views.py class QuotesDetail(DetailView): model = QuotesHonors template_name = 'quotes/quotes_detail.html' def get(self, request, … -
Django request.POST not passed to form.data
I have a form, but request.POST is not passing data to my form. i.e. form.data is empty my form class DPStatusForm(forms.Form): status = forms.ChoiceField(label="") def __init__(self, excluded_choice=None, *args, **kwargs): super().__init__(*args, **kwargs) if excluded_choice: status_choices = ( (s.value, s.label) for s in DP.Status if s.value != excluded_choice ) else: status_choices = ((s.value, s.label) for s in DP.Status) self.fields["status"].choices = status_choices view to receive form data def update_status(request, id): if request.method == "GET": return redirect("my_app:show_dp", id) p = get_object_or_404(DP, pk=id) form = DPStatusForm(request.POST) # debug statements print(request.POST) print(form.data) # ... With the 2 print statements, I can see that request.POST is present with status key populated, but form.data is empty: # request.POST <QueryDict: {'csrfmiddlewaretoken': ['xxx...], 'status': ['1']}> # form.data <MultiValueDict: {}> Why is form.data not getting populated? -
Create sqlalchemy engine from django.db connection
With DJANGO app and postgresql db, I use panda read_sql quite a bit for rendering complex queries into dataframe for manipulation and ultimate rendering to JSON. Historically have used django.db dbconnections to map from multi db environment and pass that connection directly into read_sql function. As panda evolves, and becomes less tolerant of non sqlalchemy connections as an argument, I am looking for a simple method to take my existing connection and use it to create_engine. I've seen some related past comments that suggest engine = create_engine('postgresql+psycopg2://', creator=con) but for me that generates an error: TypeError: 'ConnectionProxy' object is not callable I've played with various attributes of the ConnectionProxy...no success. Would like to avoid writing a separate connection manager or learning too much about sqlalchemy. Django is using psycopg2 to create its connections and I am long time user of same. Some of the add-ins like aldjemy are too intrusive since I neither need or want models mapped. Some have suggested ignoring warning message since dbconnection still works...seems like risk longterm... -
Count before filter in django
I have a ModelViewSet with their own filter. class XList(viewsets.ModelViewSet,): serializer_class = serializers.XXX queryset = models.XXX.objects.all() lookup_field = 'field_id' filter_backends = [DjangoFilterBackend] filterset_class = filters.MYOWNFILTER I want show in response the count of data before and after filtering. My desired answer would be, { "next": 2, "previous": null, "count": 20, "TOTAL_COUNT": 100 "size": 10, "results": [ {} ] } where TOTAL_COUNT would be the total count of data before any filter, and count, the count of data after filter. Now, I've got the following response. I need the total count. { "next": 2, "previous": null, "count": 20, "size": 10, "results": [ {} ] } I'm using pagination to get the response. def get_paginated_response(self, data): return Response({ 'next': self.page.next_page_number() if self.page.has_next() else None, 'previous': self.page.previous_page_number() if self.page.has_previous() else None, 'count': self.page.paginator.count, 'size': len(data), 'results': data -
How to make dynamic url on HTML form
I want to make web with django framework and postgres as the database. The web can add, delete and edit the table which connect with database. I've finished the add and delete button but I'm getting stuck with the edit button. I want to make edit button to edit a row data. When we click the edit button there will be a modal (like add button) that we will edit the selected row data. I use HTML form to make a form. My idea is when we click the edit button I want to collect the id of the row. So, after I submit the form to edit the data, the url redirect to /edit/int:id (urls.py) then triggered the edit function (views.py). My problem is on form action='', the url is static, I don't know to change it. Also, I hope when I click the edit button the form is filled by the old data before I edit it. Here the part of my templates <body> <h1>List Company Database</h1> <div class="topsection" style=f> <div class="float-end topsectionbutton"> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modalAdd" data-backdrop="static" data-keyboard="false" style="cursor:pointer">Add</button> </div> </div> <hr> <table id="tableListCompany" class="table table-bordered" cellspacing="0" width="100%" style="word-break: break-word;"> <thead> <tr> <th scope="col" style="text-align:center" … -
SyntaxError: Unexpected identifier when using Rollup on Github Actions w/ pnPM
I'm building a open source documentation generator.. I am using rollup to bundle all my typescript files. It seems to work perfectly on my pc but when the build process is carried out by a Github Action it returns this Syntax error. My workflow: name: Changesets on: push: branches: - main env: CI: true PNPM_CACHE_FOLDER: .pnpm-store jobs: version: timeout-minutes: 15 runs-on: ubuntu-latest steps: - name: 🛒 Checkout code repository uses: actions/checkout@v3 with: fetch-depth: 0 - name: ⚙️ Setup node.js uses: actions/setup-node@v3 with: node-version: 14 - name: 📦 Install pnpm run: npm i pnpm@latest -g - name: ⚙️ Setup npmrc run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc - name: ⚙️ Setup pnpm config run: pnpm config set store-dir $PNPM_CACHE_FOLDER - name: ⬇️ Install dependencies run: pnpm install --frozen-lockfile - name: 📦 Build packages run: pnpm run build - name: Create and publish versions uses: changesets/action@v1 with: commit: "chore: update versions" title: "chore: update versions" publish: pnpm ci:publish env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} Workflow Logs: https://github.com/gaurishhs/documentum/actions/runs/3931056531/jobs/6721823580#step:8 -
Type hints for the generic utility in the Django
def get_or_create_object(self, model : ?(what will be the type?), data: dict) -> ? (what will be the return type): try: obj, _ = model.objects.get_or_create(**data) except model.MultipleObjectsReturned: obj = model.objects.filter(**data).first() return obj get_or_create_object(ModelName, data) What will be the type hint here - as function will get the Model instances dynamically. -
Sourcemap is likely to be incorrect: a plugin (terser) was used to transform files, but didn't generate a sourcemap for the transformation
I'm trying to upgrade mui, rollup, nodejs and npm but encountered this errorenter image description here tsconfig all packages are in their latest version tried these: Rollup is not generating typescript sourcemap How to get rid of the "@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps." warning? rollup-plugin-sourcemaps -
How can I get the incoming value of a property that is calculated from related objects in a model's clean method
I have two models, an Invoice model and a LineItem model. The LineItem model looks like this: class LineItem(models.Model): unit_price: models.DecimalField() quantity: models.IntegerField() @property def lineitem_total(self): return self.unit_price * self.quantity The Invoice model also has a total property, which returns the sum of the total of all of the related line items. Now, when the line items related to an invoice get updated, I need to validate if the total property on the Invoice exceeds a certain maximum value. However the clean() method on the Invoice fires before the related line items get updated, so it still returns the old value. I need the validation to happen on the model itself rather than a form. Is there a way to validate the line items? I've tried putting the validation in the Invoice model's clean() method, however the total property still returns the old value before the line items are updated. I've also tried raising a ValidationError in the Invoice model's save() method, however that returns a 500 error. -
Getting an ID (pk) from model.py in django-forms. Bad performance
I can't get the id through the form. I would like to pass variables to SpotifyData but they cannot be "name" values. I need to pass "id" variables. I also have another problem with ArtistForm. I have 90000 different artists in the Artist model so it takes a very long time to load the page using this form (it has to load all this values into the choicefield list) models.py from django.db import models class Region(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Rank(models.Model): name = models.IntegerField() def __str__(self): return self.name class Chart(models.Model): name = models.CharField(max_length=8) def __str__(self): return self.name class Artist(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Title(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=60) def __str__(self): return f"{self.artist} - {self.name}" class SpotifyData(models.Model): title = models.ForeignKey(Title, on_delete=models.CASCADE) rank = models.ForeignKey(Rank, on_delete=models.CASCADE) date = models.DateField() artist = models.ForeignKey(Artist, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) chart = models.ForeignKey(Chart, on_delete=models.CASCADE) streams = models.IntegerField() def __str__(self): return str(self.title) + ", " + str(self.date) + ", " + str(self.artist) \ + ", " + str(self.region) + ", " + str(self.chart) + ", " + str(self.streams) forms.py from django import forms from .models import * from spotify_data.models import (Region, Rank, Chart, Artist, Title, … -
How to show the value of Model Class Field dynamically in Django Rest Framework
I am new to django. I have following models: class MeetingUpdate(models.Model): meeting = models.ForeignKey("Meeting", on_delete=models.CASCADE) employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.TextField() class Meeting(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE) name = models.CharField(max_length=128, unique=True) created_at = models.DateTimeField() class Team(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField("Employee") class Employee(models.Model): name = models.CharField(max_length=128) This is my viewset: class MeetingUpdateViewSet(ModelViewSet): serializer_class = serializers.MeetingUpdateSerializer queryset = MeetingUpdate.objects.all() When I hit the API, I want to show the values of employee attribute dynamically based on the attribute value of meeting selected inside MeetingUpdate Model class. Employee attribute should display only those employees which are in a particular team,instead of showing all the employees.In my MeetingUpdateModel class, I have an attribute Meeting, which further has attribute team, which will tell about a particular team. We can access members that are in a particular team. How to do it? -
Python, Django, Hope to save a user's click event to database immediately, when clicking <a href...> link
I'm a newbie on programming and English is not my mother tongue. Also it is the first time to leave a question. Until now I just solved the problems by searching, reading and trying when I had a question. But I couldn't get any answer to solve my problems for now. So I post my question with a broken English. I'm developing a web with Python, Djanog. When a vistor clicking a link <a href="tel:00-0000-0000-0000">00-0000-0000-0000</a> on my web page, hope to save this event into my database(mysql) immediately. A user visits on index page, def storekeylog() makes data like IP, Full_query, Key_input and so on. then save it to database(def keylog()) in real time. For it, a user doesn't need to do anything. I use datatables(https://datatables.net/). At first, I was trying to use Ajax, but I couldn't get any result. On Ajax and Datatales, I didn't know before, but I met them in here. I can check it on my page 'mydomain.net/docu/keylog_list/' It works well. But I don't know how to save a user's click event on index page to database, then show it on 'mydomain.net/docu/keylog_list/' as well. My goal is to check a user with a specific query(keyword from … -
How to encrypt decrypted text by django-fernet-fields?
I am using django-fernet-fields, and documentation says By default, django-fernet-fields uses your SECRET_KEY setting as the encryption key. my SECRET_KEY in django is the one created by django let say it is "XXXX". my dectypted text is "gAAAAABfIrFwizr11ppteAXE3MOMItPDNfNkr5a4HcS3oiT7ih4Ln7y6TeCC5uXWPS3Yup_0s7whK3T44ndNlJRgc0Ii4_s3_A==" when I try to encrypt it by using the code below token = SECRET_KEY f = Fernet(token) d =f.decrypt(b"gAAAAABfIrFwizr11ppteAXE3MOMItPDNfNkr5a4HcS3oiT7ih4Ln7y6TeCC5uXWPS3Yup_0s7whK3T44ndNlJRgc0Ii4_s3_A==") print(d) it throws an error, error is ValueError: Fernet key must be 32 url-safe base64-encoded bytes. how can i avoid this error? -
Django CaptureQueriesContext can't see my objects filter query in captures_queries
I want to log the raw SQL statements in my Django testcases. I can see the INSERT sql statements, but I can't see the SELECT sql statements in the log. I want to see every SQL statement in the log, whether it is CREATE, SELECT, UPDATE or something else. Output $ python manage.py test <OUTPUT OMITTED> Found 1 test(s). Running tests... ---------------------------------------------------------------------- [{'sql': 'INSERT INTO "myapp_testtabletwo" ("test_field") VALUES (\'abc\') RETURNING "myapp_testtabletwo"."id"', 'time': '0.001'}] . ---------------------------------------------------------------------- Ran 1 test in 0.113s OK Destroying test database for alias 'default'... Closing active connection tests.py from django.db import connection from my_app.models import TestTableTwo class DatabaseExampleTests(TestCase): databases = '__all__' def test_example(self): with CaptureQueriesContext(connection) as ctx: created_object = TestTableTwo.objects.create(test_field="abc") all_objects = TestTableTwo.objects.all() print(ctx.captured_queries) models.py from django.db import models class TestTableTwo(models.Model): id = models.AutoField(primary_key=True) test_field = models.CharField(max_length=100, blank=True, null=True) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': "testpostgres", 'USER': "postgres, 'PASSWORD': "password", 'HOST': "postgres" } } Version $ python -V Python 3.9.15 $ pip list # output omitted Package Version ---------------------- --------- Django 4.1 psycopg2 2.9.5 -
Django admin inline template for specific field
I have a page like this in site-admin. This is the Inline class class InvoicePaymentInline(admin.TabularInline): model = InvoicePayment raw_id_fields = ("invoice",) extra = 1 readonly_fields = ( "is_paid", "is_active", "paid_amount", "total_amount", "date_due", "date_paid", "deferred_payment_amount", "actions", ) formset = InvoicePaymentFormSet actions_template = get_template("admin/basetransactionlog_invoicepayment.html") @model_admin.display def actions(self, item: InvoicePayment) -> str: return self.actions_template.render({"payment": item}) @model_admin.display(boolean=True) def is_active(self, item: InvoicePayment) -> bool: return item.invoice.is_active @model_admin.display(boolean=True) def is_paid(self, item: InvoicePayment) -> bool: return item.invoice.is_paid ... What I want to do is to render invoice field with a specific template. Is that possible? -
React + Django - Access has been blocked by CORS
I'm trying to make an app using django and react which is gonna catch some data from twitter. Firstly I tried to catch data by directly from front end - React App - Issue with CORS - access to fetch has been blocked by cors policy , but I was told that I should do it from backend (if I correctly understood) and I tried to do it like that: views @api_view(['GET']) def getTweets(request, username="twitterdev"): auth = tweepy.OAuthHandler(api_key, api_key_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) user1 = api.get_user(screen_name=username) return Response(user1._json) *used variables like api_key etc are being imported from other file. *do not pay attention that view is called getTweets and is getting user data. I want to change it when I get rid of CORS issues export default function Home(){ const [content, setContent] = useState(); useEffect(() => { const url = "http://127.0.0.1:8000/api/get"; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', } }) .then((response) => { if(response.status === 404){ console.log('404'); } else{ console.log(response.status) } }) .then((data) => { setContent(data) }) .catch((e) => { setContent(e.message); }) }, []) return(<div>{content}</div>) } but I'm still getting the same result. What am I doing wrong ? Is my approach to this case correct in anyhow … -
How I control not defined URLs in Django
My declared paths are urlpatterns = [ path('admin/', admin.site.urls), path('projects/',include('projects.urls')), path('', include('users.urls')), ] if user enter wrong URLs outside of my deceleration. How I control That? urlpatterns = [ path('admin/', admin.site.urls), path('projects/',include('projects.urls')), path('', include('users.urls')), ] -
How to load up the whole Django project (including js files) when testing with webdriver in Selenium?
I am using Selenium to test my Django project's JavaScript. The web driver is getting the index.html which is the home page but the JavaScript is not loading up in my index.html page (as if I were running the whole project, not individual page/template). How do I load up the whole Django project for the web driver to get the intended result? I ran the test file and got the following error: "self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100) AssertionError: '{{ usd|intcomma }}' != 100" {{ usd|intcomma }} is templated as I believe other files in my Django project is not loading up. I was expecting it to be 0 initially, then becomes 100 after the click button in the test. from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By def file_uri(filename): return pathlib.Path(os.path.abspath(filename)).as_uri() driver = webdriver.Chrome(ChromeDriverManager().install()) class ClientSideTests(unittest.TestCase): def test_deposit_withdraw(self): driver.get(file_uri("portfolio/templates/portfolio/index.html")) balance = driver.find_element(By.ID, "cash-table-usd").text driver.find_element(By.ID, "cash-amount").send_keys(100) cash_submit = driver.find_element(By.ID, "cash-button") cash_submit.click() self.assertEqual(driver.find_element(By.ID, "cash-table-usd").text, 100) if __name__ == "__main__": unittest.main() -
Getting code signature issue for python's lib-dynload library in macos ventura
I have configured apache server for my Django app using mod_wsgi module. So after the configuration when I am trying to start the server, it is throwing error and I am seeing the below logs for the lib-dynload library. I tried self-signing this library but still it is giving me the same error. ImportError: dlopen(/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so, 0x0002): tried: '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?)) Can someone share any ideas on this issue, I am stuck on this for a long time. Not able to bring up my django app using apache because of this error. -
Wagatail Custom User models not displaying ModelChoiceField
Im using wagtail 4.1 & Django 4.1 I'm trying to create a custom User model which selects from a Snippet I have created. class User(AbstractUser): custiommodel= models.ForeignKey(CustomModel, on_delete=models.SET_NULL, null=True, blank=False) user_type = models.CharField(blank=False, null=False, max_length=20, choices=USER_TYPE_CHOICES) panels = [ FieldPanel('custommodel'), FieldPanel('user_type'), ] class CustomUserCreationForm(UserCreationForm): user_type = forms.ChoiceField(required=True, choices=USER_TYPE_CHOICES, label=_("User Type")) custommodel = forms.ModelChoiceField(queryset=CustomModel.objects, required=True, label=_("Select Organisation")) In my settings I have WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm' This used to previously work on older versions of wagtail. Now the only custom filed i can see from above is 'user_type' which means it's finding the correct file but won't display custom models. Is this related to this bug which won't allow me to directly register_snipets in the model file but instead in 'wagtail_hooks.py' through view sets?