Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I eliminate the segfaults that occur in working code only when debugging with ipdb?
I am using: Python: 3.11.0 Django: 4.2.8 djangorestframework 3.14.0 sqlite: 3.38.5 When I'm debugging and I use 'n' to go over a method, I sometimes get a segfault where there is no problem running the code normally. I can move my 'ipdb.set_trace()' to immediately after the call that caused the segfault, rerun the test and continue debugging but this is tedious. One cause I've tracked, is under the django reverse function. Here, the <URLResolver <module 'rest_framework.urls' from '/home/paul/wk/cliosoft/sosmgrweb/venv/lib/python3.11/site-packages/rest_framework/urls.py'> (rest_framework:rest_framework) 'api-auth/'> causes the segfault when its _populate method is invoked. I could start upgrading everything but this is a large application with many dependencies and I'd like to be confident that this problem will be eliminated if I go down that road. Does anyone know what the cause of this is and how I can resolve it? -
create choices dynamically in django
I'm trying to populate choices in django form dynamically, the choices cames from an external API. My model so far: from django.db import models class MyModel(models.Model): choice_field = models.CharField(max_length=100, choices=()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) api_url = 'http://api.com' response = requests.get(api_url) if response.status_code == 200: data = response.json() options = [(option['value'], option['label']) for option in data] self._meta.get_field('choice_field').choices = options however, it is not working, can someone help me? -
Why is my stopwatch adding fixed amount of time when I refresh?
I have a Vue.js Script is Adding time to my stopwatch once I refresh the page - Always adds an additional 6 hours. The script is simply a button that tracks time when clicked, and post the time to a django model once stopped. I am able to track time fine, but when I refresh the page, I come back to seeing 6 hours added to my stopwatch: Vue.js Script: var NavbarApp = { data() { return { seconds: {{ active_entry_seconds }}, trackingTime: false, showTrackingModal: false, timer: null, entryID: 0, startTime: '{{ start_time }}' } }, delimiters: ['[[', ']]'], methods: { startTimer() { fetch('/apps/api/start_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.startTime = new Date() this.trackingTime = true this.timer = setInterval(() => { this.seconds = (new Date() - this.startTime) / 1000 }, 1000) }) }, stopTimer() { fetch('/apps/api/stop_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.entryID = result.entryID this.showTrackingModal = true this.trackingTime = false window.clearTimeout(this.timer) }) }, discardTimer() { fetch('/apps/api/discard_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token … -
How to Efficiently Create and Maintain SQL Indexes in Django with PostGIS?
I'm working on a Django project that utilizes PostGIS for spatial data. Currently, I'm considering creating a SQL index for the created_at field to improve query performance. The created_at field is configured with auto_now_add=True, meaning it automatically captures the timestamp when an object is created. However, I'm unsure about the best practices for creating and maintaining SQL indexes in Django with PostGIS. Here are my specific questions: What is the recommended approach for creating SQL indexes in Django with PostGIS? Does creating an index for the created_at field significantly improve querying performance in Django? What are the potential maintenance tasks associated with managing SQL indexes in Django with PostGIS? I would appreciate any insights, advice, or best practices from experienced Django developers or those familiar with working with PostGIS. Thank you! -
Django: Mocking an external api call in the save method of a model
I want to test a modelform using pytest in two modes: without the need to call the external API used in the save method by generating an error when the API is offline so I can test the validation I created Here's my code: trips/models.py class Place(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name="places") day = models.ForeignKey( Day, on_delete=models.SET_NULL, null=True, related_name="places" ) name = models.CharField(max_length=100) url = models.URLField(null=True, blank=True) address = models.CharField(max_length=200) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) objects = models.Manager() na_objects = NotAssignedManager() def save(self, *args, **kwargs): old = type(self).objects.get(pk=self.pk) if self.pk else None # if address is not changed, don't update coordinates if old and old.address == self.address: return super().save(*args, **kwargs) g = geocoder.mapbox(self.address, access_token=settings.MAPBOX_ACCESS_TOKEN) self.latitude, self.longitude = g.latlng return super().save(*args, **kwargs) def __str__(self) -> str: return self.name trips/forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = ["name", "url", "address", "day"] formfield_callback = urlfields_assume_https widgets = { "name": forms.TextInput(attrs={"placeholder": "name"}), "url": forms.URLInput(attrs={"placeholder": "URL"}), "address": forms.TextInput(attrs={"placeholder": "address"}), "day": forms.Select(attrs={"class": "form-select"}), } labels = { "name": "Name", "url": "URL", "address": "Address", "day": "Day", } def __init__(self, *args, parent=False, **kwargs): super().__init__(*args, **kwargs) if parent: trip = parent else: trip = self.instance.trip self.fields["day"].choices = ( Day.objects.filter(trip=trip) .annotate( formatted_choice=Concat( "date", Value(" (Day … -
Cant get Django Date Widget to show in form
I am attempting to get a date field in a form to display as a date with date picker. For some reason, the field will not display as a date type. The model field: registration_date = models.DateField(null=True, blank=True) The form: class VehicleQuickAdd(forms.ModelForm): class Meta: model = Vehicle fields = ['license_plate', 'internal_id', 'affiliated_company', 'registration_date', 'active_since', 'registration_certificate',] widgets = { 'registration_date': forms.DateInput(attrs={'type': 'date'}) } The HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Add Vehicle{% endblock title %} {% block content %} <div class="section-container container-fluid"> <div class="general-form pl-md-5 pr-md-5"> <h2>Add Vehicle</h2> <form action="" method="post"> {% csrf_token %} {% crispy form %} </br> <input class="btn btn-success" type="submit" value="save"> </form> </div> </div> {% endblock content %} When I look at the element in the page it says type="text" <input type="text" name="registration_date" class="dateinput form-control" id="id_registration_date"> Any ideas about why this isn't working? -
Annotations returning pure PK value instead of Django HashID
In my application the user can assume one of 3 different roles. These users can be assigned to programs, and they can be assigned to 3 different fields, each of those exclusevely to a role. In my API I'm trying to query all my users and annotate the programs they are in: def get_queryset(self): queryset = ( User.objects .select_related('profile') .prefetch_related('managed_programs', 'supervised_programs', 'case_managed_programs') .annotate( programs=Case( When( role=RoleChoices.PROGRAM_MANAGER, then=ArraySubquery( Program.objects.filter(program_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.SUPERVISOR, then=ArraySubquery( Program.objects.filter(supervisors=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.CASE_MANAGER, then=ArraySubquery( Program.objects.filter(case_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), default=Value(list()), output_field=ArrayField(base_field=JSONField()), ) ) .order_by('id') ) return queryset This works (almost) flawlessly and gives me only 5 DB hits, perfect, or not... The problem is that I'm using Django HashID fields for the Program PK, and this query returns the pure integer value for each Program. I've tried a more "normal" approach, by getting the data using a SerializerMethodField: @staticmethod def get_programs(obj): role_attr = … -
Django: changing contents on a field on every save-like action
Before committing a record to the database, I want to do a sanity check on a certain field. More precisely, it is an ArrayField and I want to remove any NaN/None values and replace them by zero. However, there are many ways to create said record. A user might MyObject().save(), or MyObject.objects.create(), or MyObject.objects.bulk_create(), and even MyObject.objects.bulk_update(field=my_field). I believe there are also ways in that Django Rest Framework might use. How can I be sure that NaN/None is always replaced by zero before committing to the database? Should I overwrite all the above methods? Should I create a custom field that inherits from ArrayField but does all the data munging? What is the best practice? -
How to disable Socket io?
I am making a project involving django, react with websockets. First I tried to use socket.io, completed its setup , then decided not to use it. I deleted the files related to that but this error is popping every few seconds when i run my backend server, How to stop this? I tried to remove the server.js file , still it is persistent enter image description here -
In add to cart Span is not working properly
I Created a add to cart function for my website but in the website span is not working properly . My problem is that: You can see in the marked portion of the image if i clicked on add to cart button it is changing "0-1" but when I am clicking on add to cart button of an another product it is not changing from "1-2" So, In product-detail.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In js file: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In Views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) So please help me out with this problem and I think that the probelm is in views because js file is working properly... -
Changing ImageField URL
I'm attempting to correct my image URLs by invoking the correct_image_url method of the Page model. However, for some reason, the result is not being saved. Thus, while it operates correctly, at the step where I execute: print(f"New URL of the page: {new_image_url}") it returns the old URL. class Page(models.Model): image = models.ImageField( max_length=400, storage=S3Boto3Storage(), validators=[FileSizeValidator(limit_value=8)]) number = models.PositiveIntegerField(default=0, blank=True, null=True) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) objects = PageManager() def correct_image_url(self): url = self.image.url corrected_url = url.replace( "https%3A/dist.cloudfront.net", "https://dist.cloudfront.net") domain = "https://dist.cloudfront.net" first_occurrence = corrected_url.find(domain) second_occurrence = corrected_url.find( domain, first_occurrence + len(domain)) if second_occurrence != -1: corrected_url = corrected_url[:second_occurrence] if corrected_url != url: if self.image: original_url = self.image.url print( f"Correcting URL from: {original_url} to {corrected_url}") self.image = corrected_url try: self.save() self.refresh_from_db() new_image_url = self.image.url print(f"New URL of the page: {new_image_url}") except DataError: print( f"Skipped saving due to DataError for URL: {corrected_url}") except ValidationError as e: print( f"Validation error: {e.messages} for URL: {corrected_url}") I run it in the Django shell like this: from app.models import Page for page in Page.objects.all()[:1]: page.correct_image_url() Also, when i try to run self.image.url = corrected_url It returns AttributeError: can't set attribute -
Best practice for tenant isolation with django-tenant-users in Django?
I'm building a multi-tenant application using Django with django-tenant and django-tenant-users for handling tenants and user authentication. However, I'm struggling to find the best approach to prevent users from one tenant accessing data or functionality of another tenant. I've explored custom middleware, Django's permission system, and user profile models, but haven't found clear guidance on enforcing tenant isolation within the Django framework. For those familiar with django-tenant and django-tenant-users, how do you ensure that users from one tenant cannot access data or features belonging to another tenant? Any insights, best practices, or references to relevant documentation would be greatly appreciated. Thank you! -
Can't run my Django app on hosting with Debug = False
I tried running my Django app on hosting, but when i typed python manage.py runserver with DEBUG = False, it threw me an error: Error: That IP address can't be assigned to. After that changed DEBUG to True, but it continued to throw me the same error. What should i do to solve it? Tried to add my domain in ALLOWED_HOSTS, didnt work. Put 127.0.0.1 and localhost - same -
Unable to read Local language data from an Excel using csv
I am giving data as "यह एक नमूना संदेश है" in a CSV file. I am reading the data inside the file using CSV Module in python. sample code: csvFile = request.FILES.get('file') csv_copy = copy.deepcopy(csvFile) file_content = csv_copy.read() decoded_file = file_content.decode('utf-8').splitlines() reader = csv.reader(decoded_file) rows = list(reader) for i,row in enumerate(rows): print(row[1]) the given data is getting converted as "???? ???? ???" Is there any way to resolve this issue ? -
django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm learning Django but I keep getting this error when I type : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I Have a Creating Superuser But I'm facing some Error till superuser run on Server. So, Give me A Solution of This Error. My models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone = models.CharField(max_length=10) cpassword = models.CharField(max_length=10) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ("email",) objects = CustomUserManager() -
Convert Django-React dynamic website to static site
I want to convert my personal portfolio website here into a static site. Currently, I am deployed on AWS Elastic Beanstalk which has gotten expensive over the last year or so, due to me running out of AWS free tier. I'd like to convert the following routes: https://www.tomaspremoli.com/ https://www.tomaspremoli.com/#/tutoring https://www.tomaspremoli.com/#/portfolio https://www.tomaspremoli.com/#/resume into static html pages, save all images that are fetched in the code, and save all api call responses. Some api calls just run on page load, however, some api calls happen in js after buttons are clicked (such as when getting pictures for specific portfolio entries). I have access to the source code and all the root user permissions, and am not sure what the best course of action is here. I can't seem to find a tool that does this for me easily, and have been toying around with the Pupeteer js library, with some progress, but also out of my area of expertise and struggling to get much done. Is there any tools that could simplify this for me? So far i've tried various manual processes that don't seem to get me very far. -
Django-server fails for ModuleNotFoundError: No module named '_ldap' when started by apache
When started in python 3.9 virtual environment by python manage.py runserver my django-server works fine, but when started by apache with the same virtual environment configured into python path it fails with the errors below: [Mon Mar 11 11:00:49.683439 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] from .ldapauth import * [Mon Mar 11 11:00:49.683446 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] File "/srv/django/pxpro/pxpro_editor/ldapauth.py", line 4, in <module> [Mon Mar 11 11:00:49.683495 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] import ldap [Mon Mar 11 11:00:49.683501 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] File "/srv/django/pxpro-env/lib/python3.9/site-packages/ldap/__init__.py", line 34, in <module> [Mon Mar 11 11:00:49.683504 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] import _ldap [Mon Mar 11 11:00:49.683512 2024] [wsgi:error] [pid 909852:tid 139790141196032] [remote 10.144.196.5:52892] ModuleNotFoundError: No module named '_ldap' I'm using django 4.2.10 with pyldap==3.0.0.post1 and python-ldap 3.4.4 in my python virtual environment my apache.conf: $ cat /etc/httpd/conf.d/pxpro.conf <VirtualHost *:8031> ServerAdmin <myserverAdmin> ServerName <myServer> # ServerAlias <server_fqdn> ErrorLog /var/log/httpd/pxpro-error_log CustomLog /var/log/httpd/pxpro-access_log combined LogLevel debug HostnameLookups Off UseCanonicalName Off ServerSignature Off Alias /media/ /srv/django/pxpro/media/ Alias /static/ /srv/django/pxpro/static/ #RedirectMatch 301 "^/static/media/uploads/(.*)$" "/media/uploads/$1" <IfModule wsgi_module> WSGIDaemonProcess pxpro_wsgi user=django group=django home=/srv/django python-home=/srv/django/pxpro-env startup-timeout=15 python-path=/srv/django/pxpro-env/lib/python3.9/site-packages WSGIProcessGroup pxpro_wsgi WSGIApplicationGroup pxpro_wsgi WSGIScriptAlias / /srv/django/pxpro/settings/wsgi.py process-group=pxpro_wsgi application-group=pxpro_wsgi </IfModule> ... Any idea … -
Im getting this error in my file in my decorate.py file
This is the error i get Although I tried to remove the httpresponse from my code even that isn't solving the issue. from multiprocessing import context from django.http import HttpResponse from django.shortcuts import redirect, render def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.authenticated: return redirect('homepage') else: return view_func(request,*args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request,*args, **kwargs): group is not None if request.user.groups.exists(): group=request.user.groups.all()[0].name if group in allowed_roles: return view_func(request,*args, **kwargs) if group == 'user': return render(request,'loginapp/user_dashboard') '''else: return HttpResponse('you are authorized')''' return wrapper_func return decorator def admin_only(view_func): def wrapper_func(request,*args, **kwargs): group is not None if request.user.groups.exists(): group=request.user.groups.all()[0].name if group == 'user': return render(request,'loginapp/user_dashboard') if group == 'admin': return render(request,'loginapp/admin_dashboard') return wrapper_func .......................................................................... -
Task Queue with cached libraries in Django
I am creating a WEB interface for various Python scripts through Django. Example in calculation.py I would have : import datetime def add_time(a, b): return = a + b + int(datetime.datetime.now()) Usages : A user could say "I want to run add from calculation.py with arguments [1, 3]" and that returns him the result when it's ready. A user could say "I want this to run add from calculation.py with arguments [1, 3] every 10 minutes and check if result is greater than X" and that would action something if it's true. Most of my script functions are quick but they need to import libraries that takes a lot of time to load. I am currently doing this directly with my Django service ; it's simple and load the libraries once which allows most of the next calls to be very fast but sometimes a heavy call is made and that is slowing down all my Django application and I seem limited if I want to have CRON scheduling for some scripts. Therefore I am looking at another solution. I started to look at : Celery (but it seems not supported anymore on Windows) Huey and Dramatiq Django-Q2 (easy to … -
Using slugs with Django (Form + Model)
I have the following error: Error in page Django admin DB Shell object The logic that I use in Django is based on a model and the ModelForm class. Here is the model: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse class Ingredient(models.Model): name = models.CharField(max_length=100) def __str__(self): return f'{self.name}' class Recipe(models.Model): slug = models.SlugField(null=True, unique=True, blank=True, editable=False) title = models.CharField(null=False, max_length=100) description = models.CharField(null=False, max_length=250) preparation = models.TextField(null=False) score = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) last_update = models.DateField(auto_now=True) presentation_image = models.ImageField(upload_to='images', null=True, blank=True) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return f'{self.slug}, {self.title}, {self.description}, {self.preparation}, {self.score}, {self.last_update}, {self.presentation_image}, {self.ingredients}' Here is the RecipeForm: from django import forms from django.core.validators import MinValueValidator, MaxValueValidator from .models import Recipe from .models import Ingredient class RecipeForm(forms.ModelForm): class Meta: model = Recipe exclude = ['slug', 'last_update'] widgets = { 'preparation': forms.Textarea() } labels = { 'title': 'Title', 'description': 'Description', 'preparation': 'Preparation', 'score': 'Score', 'presentation_image': 'Presentation Image', 'ingredients': 'Ingredients' } I understand that the problem is based on the fact that no slug is generated (since it is None in the shell). Since my path for a single recipe is based on a slug then Django simply tells me "Hey dude, no slug to … -
split payments using stripe in django
I am working on a project where, buyer will make the payment and that payment should be split into application-fee seller payment referral payment her is my code if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + taxes # if referrals: admin_amount = int((total_charges - shipping_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) payment_info = { "amount": total_charges, # Amount in cents "currency": "usd", "connected_accounts": [ {"account_id": 'acct_1OoODQIbLDChIvG2', "amount": seller_amount}, {"account_id": "acct_1OrzPRI5g3KKKWKv", "amount": referral_amount}, ] } stripe.api_key = "sk_test_EI5Kddsg2MCELde0vbX2cDGw" try: for account_info in payment_info["connected_accounts"]: # Set up transfer amount and destination separately transfer_amount = account_info["amount"] destination_account = account_info["account_id"] print("=======================================================", destination_account) session = stripe.checkout.Session.create( success_url=my_domain + '/payment_success/' + str(auction_id) + '/' + courier_id + "?mode=" + mode, cancel_url=my_domain + '/payment_failed/' + str(auction_id) + '/' + courier_id + "?mode=" + mode, payment_method_types=['card'], mode = 'payment', line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'NailSent Nails', }, 'unit_amount': int(total_charges), # amount should be in cents }, 'quantity': 1, }], payment_intent_data={ 'transfer_data': { 'destination': destination_account, 'amount': transfer_amount, # amount should be in cents } }, ) except stripe.error.StripeError as e: return HttpResponse(f"Error: {e}") i was trying to split … -
"AttributeError: 'NoneType' object has no attribute 'startswith' in Django Djongo"
I am encountering an AttributeError in my Django application while using Djongo as my database backend. The error message is as follows: AttributeError at /loginPage 'NoneType' object has no attribute 'startswith' This error occurs in the quote_name method in operations.py. Here is the relevant code snippet: class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name return '"{}"'.format(name) I understand that this error typically arises when a method is called on a NoneType object, but I'm unsure why it's happening in this context. Could anyone please provide insights into why this error might occur and how to resolve it? I'm using Django with Djongo as my database backend. Additionally, I'm trying to implement functionality where form data goes to two different collections in my MongoDB database. I've attempted to modify the code accordingly, but I'm encountering this error. Below is a snippet of the code where the error occurs: #forms.py class UserAdminCreationForm(UserCreationForm): company_name = forms.CharField(max_length=100) ROLE_CHOICES = [ ('admin', 'Admin'), ('user', 'User'), ] role = forms.ChoiceField(choices=ROLE_CHOICES, label='Role') email = forms.EmailField(required=True) class Meta: model = get_user_model() fields = ['company_name','role','first_name', 'last_name','email', 'password1', 'password2',] def save(self, commit=True): user = super().save(commit=False) # Get the user object without saving to the database yet user.company_name … -
Wagtail How to get the value of an orderable
I am a relative newcomer to programming Wagtail My attempt is a cascaded application where the title is formed from the relation to the underlying element. The cascade should be structured like this Fach --> Reihe --> Ebene --> Behaelter My models.py from django.db import models from django.utils.text import slugify from wagtail.models import Page from wagtail.admin.panels import FieldPanel # InlinePanel # PageChooserPanel from django import forms from wagtail.admin.forms import WagtailAdminPageForm from django.utils.translation import gettext_lazy as _ # Create your models here. class NoTitleForm(WagtailAdminPageForm): title = forms.CharField(required=False, disabled=True, help_text=('Title is autogenerated')) slug = forms.CharField(required=False, disabled=True, help_text=('Slug is autogenerated')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.initial['title']: self.initial['title'] = _('auto-generated-title') if not self.initial['slug']: self.initial['slug'] = _('auto-generated-slug') class ReihePage(Page): base_form_class = NoTitleForm content_panels = [ MultiFieldPanel( [ InlinePanel("Fach", label="Fach", min_num=0, max_num=10), ] ), FieldPanel('title'), FieldPanel('slug'), ] def clean(self): super().clean() new_title = "anzahl from Fach" + "title from Fach" <--** How to get the values from the InlinePanel** self.title = new_title self.slug = slugify(new_title) class ReihePageOrderable(Orderable): page = ParentalKey(ReihePage, related_name="Fach", null=True) fach = models.ForeignKey("Fachpage", on_delete=models.SET_NULL, null=True) anzahl = models.IntegerField(default=1) class FachPage(Page): laenge = models.IntegerField(null=True, blank=True, verbose_name='Länge in mm') breite = models.IntegerField(null=True, blank=True, verbose_name='Breite in mm') content_panels = [ # FieldPanel('bezeichnung'), FieldPanel('laenge'), FieldPanel('breite'), FieldPanel('title'), … -
ModuleNotFoundError: No module named " CustomModule"
I've had a problem for a week now. I can't integrate unit tests into my Django project. I wanted to test one of my models. I did the necessary import to retrieve the class from models.py. But when I run the test, I get this error: ModuleNotFoundError: No module named "application name". Despite configuring the application in setting.py in INSTALLED_APPS. All the init files are present. And I have double-checked the names. I don't know why I have this problem. When I run the runserver, I get a 200 response. Everything works, but when I try to run a test... I see this error. Thank you for enlightening me. Best regards. Creating a simple test without importing the model works. So it's definitely linked to the module. It's not being found. -
Can I connect my django app container to connect the mysql databse on my local machine?
I have a django application which is running in a container.. I was trying to connect to mysql databse running on my local machine.. In the settings.py of django project, I assing db_host to ip address my local machine for database configuration.. In container I tried to curl my local machine ip address and it worked fine.. Even then my django app gives the error..Can't connect to server on <ip_address>.. Is it even possible to connect if yes, then how?? My Dockerfile. # Use an official Python runtime as a parent image FROM python:3.9-slim # Set environment variables for Python ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory in the container WORKDIR /app # Copy the current directory contents into the container at /app COPY . /app # Install system dependencies for mysqlclient RUN apt-get update \ && apt-get install -y python3-dev default-libmysqlclient-dev build-essential pkg-config gcc curl \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies RUN pip install --upgrade pip \ && pip install -r requirements.txt # Expose port 8000 to allow communication to/from server EXPOSE 8000 # Run the Django development server CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]