Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formatting text in Python
I currently have a breadcrumb package which have successfully deployed into my website. The package displays the name of the name of the html document which is gleamed from the web directory. I'm still very new to Python. This correctly display the breadcrumb trail, however I need to format this. My code is as follows but Django appears to ignore any formatting I tell it to action. class BreadcrumbsItem: def __init__(self, name_raw, path, position, base_url=None): ..... self.remove_dashes = self.name_raw.replace("-", " ") .... def remove_dashes(self): formatted_path_name = str(name_raw) return formatted_path_name.replate("-"," ") Why are the items (page names) in the breadcrumbs in my HTML document not being removed? -
How to insert a new page data manually in wagtail database table?
I am using wagtail 2.10.2. And I want to use SQL query to manually create a page entry for a page type in database. Would like to know the steps and possible complications in doing so. Thanks How to achieve this with out breaking the existing setup which is up and running. -
Django factory-boy custom provider
I would like to create my own customer Faker provider. I am using factory-boy which comes already with Faker included, so in my test factories I am using for a UserFactory name = factory.Faker('name') My question is, can I somehow implement my own custom provider? So I could use factory.Faker('my_provider')? Or for that I would have to swap all factory.Faker() instances and just use Faker() instance? -
Error while adding exiting table from sql server in django app using django inspectdb -- error
I am try to use py -m django inspectdb , but not able to get success... I am able to connect database through django code in setting.py I am getting following error while using inspectdb command in windowds cmd shell py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py (seatenv) C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\OSeatMap\OSeatMap>py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py Traceback (most recent call last): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 58, in getitem return getattr(self._connections, alias) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\asgiref\local.py", line 105, in getattr raise AttributeError(f"{self!r} object has no attribute {key!r}") AttributeError: <asgiref.local.Local object at 0x000001B984F51750> object has no attribute 'DB_UUIS_ITO_BB' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 198, in run_module_as_main File "", line 88, in run_code File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django_main.py", line 9, in management.execute_from_command_line() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 46, in handle for line in self.handle_inspection(options): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 55, in handle_inspection connection = connections[options["database"]] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 60, in getitem if alias not … -
annotate django query by substring
How do you annotate a query set using a substring from a field? I presume something like this: query_by_domain = ( queryset .annotate(domain=Substr("email", F("email").Index("@") + 1)) .values("domain") .annotate(count=Count("id")) .order_by("domain") ) -
Is there something i am doing wrong?
import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; import '../styles/sales.css'; // Import the CSS file function Sales() { const [propertyData, setPropertyData] = useState([]); useEffect(() => { // Fetch data from your Django API using Axios axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/') .then((response) => { // Limit the photos to a maximum of four const limitedData = response.data.slice(0, 4); setPropertyData(limitedData); }) .catch((error) => { console.error('Error fetching data:', error); }); }, []); return ( <div className="sales-container"> {propertyData.map((property) => ( <div key={property.id} className="property-card"> <Link to={`/property/${property.id}`}> <img src={property.main_photo} alt={property.title} className="property-image" /> <h2 className="property-title">{property.title}</h2> </Link> <p className="property-description">{property.description}</p> <p className="property-details"> {property.bedrooms} Bedrooms | ${property.price} </p> </div> ))} </div> ); } export default Sales; I was trying to fetch data from a django-rest api. I have installed the axios library, defined the CORS_ALLOWED_ORIGINS also added the corsheaders but the images cannot be rendered. I get the following error "Error fetching data: TypeError: response.data.slice is not a function" -
how to display cart items detail in html
my views.py def cart(request): context={'cart': Cart.objects.filter(is_paid=False)} return render(request, 'cart.html',context) my models.py class Cart(models.Model): is_paid=models.BooleanField(default=False) class CartItems(models.Model): cart=models.ForeignKey(Cart, on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.SET_NULL, null=True,blank=True) color_variant=models.ForeignKey(ColorVariant, on_delete=models.SET_NULL, null=True, blank=True) size_variant=models.ForeignKey(SizeVariant, on_delete=models.SET_NULL, null=True, blank=True) my cart.html {% if cart %} <tr> {% for item in cart %} <td class="product__cart__item"> <div class="product__cart__item__pic"> <img src="{% static "img/shopping-cart/cart-1.jpg" %}" alt=""> </div> <div class="product__cart__item__text"> <h6>{{item.product.name}}</h6> <h5>98</h5> </div> </td> <td class="quantity__item"> <div class="quantity"> <div class="pro-qty-2"> <input type="text" value="1"> </div> </div> </td> <td class="cart__price">$ 30.00</td> <td class="cart__close"><i class="fa fa-close"></i></td> {% endfor %} </tr> -
Implicit UUID auto fields for primary keys in Django
By default, Django adds integer primary keys as Autofields. This is annoying for many purposes, but especially makes debugging more difficult (code may accidently refer to the wrong "id", but instead of creating a runtime error, this might work in "some" instances because the IDs are accidently the same). I want either unique integers across all tables or UUIDs for primary key. I do not want to specify either explicitly, since I want to only use this for debugging (and switch back to integers in production). This is not a new proposal, but all answers seem to say "this is not performant" (blinding flash of the obvious) or advise to use explicit UUID fields (I don't want to do this because it means changing my model EVERYWHERE, then having to change it back later). Is there a way how to achieve this? The proposals I've looked at (none of which answer by question) can be found here: Using a UUID as a primary key in Django models (generic relations impact) and Django: Unique ID's across tables with an open ticket for this feature here https://code.djangoproject.com/ticket/32577 -
Django psycopg2 error while migrating the project
The following error occurs while doing manage.py migrate. psycopg2.errors.UndefinedTable: relation "relation_name" does not exist ... ... ... django.db.utils.ProgrammingError: relation "relation_name" does not exist Happened when I tried to set up a copy of my project elsewhere. Yes, I have installed all the dependencies. -
Why is my page displaying duplicate objects during pagination?
I've added in a sort-by dropdown option to my webpage but for some reason it's displaying duplicate objects on the page. Here's how the flow goes: User lands on webpage and list of objects (these are posts from other users) are displayed. This displays as expected User then changes the drop down to sort the posts by "newest" and the webpage is reloaded but the webpage is displaying 2 of each object/post. home_page.html that the user lands on: <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <form action="{% url 'posts:dropdown_selected' %}" method="get" name="sort_form"> <select class="rounded border-gray-200" name="sort_by" onchange="sort_form.submit()"> <option id="" value="placeholder" disabled selected hidden>Sort By</option> <option value="most_supported">Most Supported</option> <option value="newest">Newest</option> <option value="oldest">Oldest</option> </select> </form> </div> </div> {% if home_search %} {% for post in object_list %} <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <a href="{% url 'posts:post_detail' post.pk %}"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <div class="bg-white px-6 py-8 rounded shadow-md text-black w-full"> <img class="lg mb-6" src="" > <h1 class="mb-8 text-3xl text-center">{{ post.title }}</h1> <p class="text-gray-700 text-base"> {{ post.description }} </p> </a> <div class="relative flex-nowrap text-gray-500 mt-8 mb-0"> {% for tag in post.tags.all %} <div class="ml-4 text-xs inline-flex items-center … -
How do I specify OpenApiParameter properties for OBJECT type?
In drf-yasg when we specify Schema we have properties argument, where we can specify fields of OBJECT type. How do I get the same behavior for drf-spectacular's OpenApiParameter? @swagger_auto_schema( summary="Wallet balance", description="Save the wallet's balance", request=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'balance': openapi.Schema(type=openapi.TYPE_NUMBER), 'some_object': openapi.Schema(type=openapi.TYPE_OBJECT, properties={ 'a': openapi.Schema(type=openapi.TYPE_STRING), 'b': openapi.Schema(type=openapi.TYPE_STRING), }), } ), ) -
How to develop an E-commerce website using Python and Django as a server side language
I want to build an E-commerce website using Bootstrap, HTML, CSS, Java script in Frontend and For backend I want to use Python, Django and MongoDB. Can I get step wise instruction to develop files of codes of each language and how to link each one of them to make fully functional website. I want to know what directories and files will get added in code editor. -
Error display in the django admin through save_model
I have the following code in one of the classes related to the admin page: def save_model(self, request, obj, form, change): if change: if form.initial['delivered'] != form.cleaned_data['delivered']: for line in obj.lines.all(): book = line.book if not book.is_available and not obj.delivered: raise ValidationError('Error') if obj.delivered: number = line.book.number + 1 line.book.is_available = True else: number = book.number - 1 if not number: book.is_available = False line.book.number = number line.book.save() obj.save() return super().save_model(request, obj, form, change) The problem is that when the code reaches the raise ValidationError('Error') line and is executed, it doesn't show the error on the page and shows it like django debug errors, and this error is displayed only when DEBUG=True. How can I show this error like the django admin form errors? I also tried this code with django signals but it had the same result. Only when I wrote a class form myself and gave it to the admin class, it displayed the error correctly, but I cannot implement the conditions here in the form class. Is there a way to fix it in the save_model? -
Django file structure: cannot import main module without export PYPATH
I am using Django 4.0.4 Here is my project structure: root/ | README.md |-- app/ | |-- init__.py | |-- manage.py | |-- project/ | | |-- __init__.py | | |-- settings.py | | |-- urls.py | | |-- etc... | |-- webapp/ | | |-- __init__.py | | |-- apps.py | | |-- views.py | | |-- utils/ | | |-- migrations/ | | |-- etc... | |-- mediafiles/ |-- docs/ The imports inside de files are structured like this: apps.py => from app.project.settings import APP_NAME settings.py => from app.webapp.utils.paths import BASE_DIR urls.py => from app.webapp.views import home views.py => from app.webapp.models import MyModel In settings.py INSTALLED_APPS = [ "webapp", ... ] In short, nothing very unusual, except that my root folder is one level higher than in a standard Django installation. However, as soon as I run python app/manage.py runserver localhost:8000 # OR python manage.py runserver localhost:8000 # (inside the `app/` directory) I get a ModuleNotFoundError: No module named 'app' The problem is fixed if I set the PYTHONPATH variable inside the root/ directory: export PYTHONPATH="$(pwd)" If I remove the app from my imports, then the command works but my IDE (PyCharm) no longer lets me take advantage … -
ExtJS paging/pagination loads all records at page load
I am trying to set up paging for a grid in my ExtJS app. Let's say I want to show 30 records per page and I have a total of 35 records. No matter what, when I visit the view, the grid always loads all 35 records in the first page although the paging bar shows the presence of two pages (see image). The navigation buttons in the paging bar don't work in that, for example, when I hit the "Next page" button, I get the following error: Uncaught TypeError: store.nextPage is not a function at constructor.moveNext (ext-all-debug.js:185314:23) at Object.callback (ext-all-debug.js:8705:32) at constructor.fireHandler (ext-all-debug.js:144259:17) at constructor.onClick (ext-all-debug.js:144241:16) at constructor.fire (ext-all-debug.js:20731:42) at constructor.fire (ext-all-debug.js:34336:27) at constructor.publish (ext-all-debug.js:34296:28) at constructor.publishDelegatedDomEvent (ext-all-debug.js:34318:14) at constructor.doDelegatedEvent (ext-all-debug.js:34361:16) at constructor.onDelegatedEvent (ext-all-debug.js:34349:18) Hitting the "Last page" button doesn't raise an error, yet it just loads the same 35 records. When I check my webserver logs, I can see that, when I visit the view, my app doesn't just request the first page of record but all of them, which makes no sense: [20/Sep/2023:10:09:55 +0200] "GET /api/requests/?page=1 HTTP/2.0" [20/Sep/2023:10:09:56 +0200] "GET /api/requests/?page=2 HTTP/2.0" I checked the API output of /api/requests/?page=1, generated by Django REST Framework, and it returns … -
Trying the 'share chat' feature for my Chatbot but its not working
I'm working on a chatbot app, and I need to add a feature in it, "share chat" which is basically the ChatGPT feature of sharing your chat. So, I'm able copy the link generated for the chat page that is opened, and when i open the link in the new tab, the page is opening as expected and we can chat in it, but only as long as we're logged in. I mean if I tried to open that link in an incognito window, or if a non-logged in user tries to open that link, it wont open. It's probably because of the @login_required decorator we are using in the Django Backend but we can't remove it since it's required for authentication. I need to a way to implement sharing the chat and even if the user is not logged in they can open and use it. The frontend is made using HTML,CSS and JS, while the backend is Python-Django. I tried opening the link without using the @login_required decorator but it was still not working. Please let me know what approach I can take here? Like what needs to be done from the backend side or frontend? -
How can i delete an object from django database after editing it?
I edited the fields of a table that had an object. i wanted to delete the object after migration but it wouldnt let me because of the different fields. how can i delete that object? i tried to revert the changes made and go delete it but it still gives errors -
Django inline admin show child of child
I have three model in a hierarchy as follows (Django): def A(models.Model): pass def B(models.Model): a = models.ForeignKey(A) def C(models.Model): b = models.ForeignKey(B) Is it possible in django-admin that I show C model as inline of A model without using nested-inlines? -
filter object by being used in other query
I am having two models. Procedures and ProcedureCategories. Now every Procedure can have a foreignkey to a ProcedureCategory. I want to do two things: Get all Procedures of a specific type for my usergroup. And get all categories that are used in these Procedures. Here are my models: class ProcedureCategories(models.Model): name = models.CharField( max_length=200, help_text="Enter category name." ) def __str__(self): return self.name def __lt__(self, other): return self.name < other.name class Procedure(models.Model): """Model representing a task (but not a specific copy of a procedure).""" title = models.CharField(max_length=200) type = models.ManyToManyField(ProcedureTypes, help_text="Select a type for this procedure") summary = RichTextField(max_length=1000, help_text="Enter a brief description of the task", blank=True) groups = models.ManyToManyField(Group, help_text="Select which groups should be assigned for the task", blank=True) category = models.ForeignKey(ProcedureCategories, on_delete=models.PROTECT, help_text="Select which category should be assigned for the task", blank=True, null=True) date_done = models.DateTimeField(null=True, blank=True) def __str__(self): """String for representing the Model object.""" return self.title The first thing is easy: procedureModels = Procedure.objects.filter(type=2, groups__user=request.user) This gives me all Procedures of type 2 with correct user group. But how can I get all ProcedureCategorires that are used in these Procedures? ProcedureCategories.filter()? I would probably need to join it somehow. How can I do this in django? -
Selenium can't reach chrome in celery task while using supervisor
I have a Django project that uses Celery as a task queue. The task is about running a chromedriver by Selenium and fetching data from some URLs. like this: @shared_task(bind=True) def task_one(self): options = Options() options.add_argument("--start-maximized") options.add_argument('--no-sandbox') options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(options=options) wait = WebDriverWait(driver, 20) action = ActionChains(driver) driver.get('https://somewhere.com') # do others This task should be run periodically, for that I use celery beat. for testing, I run celery worker and celery beat in two terminals and everything seems okay. (the celery beat sends every 20 seconds and the worker runs Chrome and fetches data) But when I use Supervisor, the worker goes wrong and can't reach Chrome. (Still celery beat works well and sends every 20 seconds but the problem is in the worker) The celery logs say: 'Message: session not created: Chrome failed to start: exited normally. (chrome not reachable) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Stacktrace: #0 0x562b0da106c3 <unknown> #1 0x562b0d6e61e7 <unknown> #2 0x562b0d719526 <unknown> #3 0x562b0d71569c <unknown> #4 0x562b0d75823a <unknown> #5 0x562b0d74ee93 <unknown> #6 0x562b0d721934 <unknown> #7 0x562b0d72271e <unknown> #8 0x562b0d9d5cc8 <unknown> #9 0x562b0d9d9c00 <unknown> #10 0x562b0d9e41ac <unknown> #11 0x562b0d9da818 <unknown> #12 0x562b0d9a728f … -
Django field not taking the given input
I have a login code in which the create two model where the data is being stored the first one is the default admin User model and the second one that is custom field Models.py from django.db import models # Create your models here. class AppUser(models.Model): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) # You should use a secure password storage method. first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) GENDER_CHOICES = [ ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ] gender = models.CharField(max_length=1, choices=GENDER_CHOICES,default='M') area = models.TextField(max_length=100,unique=False,default='Select City') phone_number = models.IntegerField(default='1') def __str__(self): return self.username and forms.py from django.contrib.auth.models import User from django import forms from .models import AppUser class SignUpForm(forms.ModelForm): GENDER_CHOICES = [ ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ] gender = forms.ChoiceField( choices=GENDER_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}), required=True, label='Gender', ) class Meta: model = AppUser fields = ['username','email','password','first_name','last_name','area','phone_number'] Now the fields till gender is working just fine but after it the area and the phone number is not taking the user input the default shows up in the table; -
conflict google-analytics-data and protobuf
I get the error "ModuleNotFoundError: No module named proto" after install the google-analytics-data package in my grpcproject. This package conflicts with protobuf==3.17.0. I have tried using different versions of google-analytics-data and protobuf, but the problem persists continues. -
Django Virtual Environment Setup
Error message in terminal : PS E:\Work space\Django> & C:/Users/hp/.virtualenvs/Django-aOoBcd7m/Scripts/Activate.ps1 & : File C:\Users\hp.virtualenvs\Django-aOoBcd7m\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & C:/Users/hp/.virtualenvs/Django-aOoBcd7m/Scripts/Activate.ps1 CategoryInfo : SecurityError: (:) [], PSSecurityException FullyQualifiedErrorId : UnauthorizedAccess how can i fix this ? I tried to change the ExecutionPolicy to RemoteSigned in powershell after that its working, but is there any other way to fix this. -
How to store or save ssh client object in Django session?
Below functions, I am creating the ssh client and trying to save it to django session object. def create_ssh_client(host, user, password): client = SSHClient() client.load_system_host_keys() client.connect(host, username=user, password=password, timeout=5000, ) return client def save_to_session(request): ssh_client = create_ssh_client(host, user, password) request.session['ssh_client'] = ssh_client ** While trying to save to session, getting the type error -** TypeError: Object of type SSHClient is not JSON serializable Any suggestion or input appreciated. -
How To Set A Related Field To Session In Django
I want to implement the Web Push Notification in my current project, and I want the notification only sent to the currently logged-in sessions (i.e. devices). Thus I define my Subscription model like below: class Subscription(models.Model): device = models.CharField(max_length=100) session = models.OneToOneField('sessions.Session', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) info = models.JSONField() and the view function to save subscription: SubscriptionForm = model form_factory(Subscription, fields=['device', 'info']) @login_required @require_POST def subscr_view(request): form = SubscriptionForm(request.POST) if form.is_valid(): form.instance.session = request.session.model form.instance.user = request.user subscr = form.save() return JsonResponse({'subscription': subscr.id}, status=201) return JsonResponse({'errors': list(form.errors.keys())}) However, when I save the form, Django complains about the session attribute: ValueError: Cannot assign "<class 'django.contrib.sessions.models.Session'>": "Subscription.session" must be a "Session" instance. How can i set the session attribute correctly?