Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin shows custom percentInput widget but in view mode values are not formatted
i am having this fancy percentinput widget that allows me to input values as if they were percents: like 47, and it saves as 0.47 decimal, but also shows me back 47.change this works perfectly for me but when the user has no right to "change" the object they all render as 0,4700 in view or readonly mode.readonly class PercentInput(NumberInput): def __init__(self, attrs=None): if attrs is None: attrs = {} attrs['type'] = 'number' attrs['step'] = 1 attrs['style'] = 'width:50px;' attrs['max'] = 100 attrs['min'] = 0.0 super().__init__(attrs) def format_value(self, value): if value == Decimal(0): return 0 if value is None: return '' return f"{value * 100}".rstrip('0').rstrip('.') # Format as percentage without decimal places #:.0f def value_from_datadict(self, data, files, name): value = data.get(name) if value: return Decimal(value) / 100 return None also the form i use class SubDealForm(forms.ModelForm): class Meta: model = SubDeal fields = '__all__' widgets = { 'player_percent': PercentInput(), 'sub_percent': PercentInput(), 'optional_rb': PercentInput(), 'wdfee': PercentInput(), } and ofc this enabled in my ModelAdmin: form = SubDealForm How to make them look formatted as percent too? without making custom duplicate functions in modelAdmin like def value_as_percent() or making custom template for it? -
Nginx Reverse Proxy's problematic behaviour
I need your help related to nginx and reverse proxy: I have a frontend running on port 80 and a backend running on port 8000 using reverse proxy in nginx both of them are being connected from same domain url (eg. https://abc123.com it is an https ->ALB{aws}->http->nginx and https://abc123.com:8000 )using different ports most of the time port 8000 pages work on alternate hits i.e for first they show a 404 and when I reload it connects, on next reload it again shows 404 and so on. I have added caching also but did not change any thing.. This port 8000 is routing to backend django server at 8001 port. Frontend is running perfectly.Backend is creating problems.. How can I resolve this? eg. For first abc123.com:8000/marvels show a 404 and when I reload it connects to corect page, on next reload it again shows 404 and so on... similar case is for all the paths related to django backend. -
How to redirect to home URL after Django Allauth login with Google?
I'm using Django Allauth to provide Google authentication for my website. Everything is working fine, except that I get redirected to 127.0.0.1:8000/accounts/google/login/callback/?state=2CXclEHzhr58&code=4%2F0Adeu5BW1_2pqwk7edcaJ7nLR7b8hmBcfRX2_605538Il2j3dWc0jYwWzEbwV10mMnmI2oA&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=2&prompt=consent# instead of just 127.0.0.1:8000/ even tho I set LOGIN_REDIRECT_URL = "home". The redirect itself works fine, in the sense that I get the home page, but is there a way to also have the link be just 127.0.0.1:8000/? Otherwise, do you know of any alternatives I could use? I'm also thinking this could be caused by Google's API, but can't tell how. Thanks in advance! Tried to set LOGIN_REDIRECT_URL = "home" and ACCOUNT_SIGNUP_REDIRECT_URL = "home" -
Why is pipenv giving me a permission error?
I tried to install django with this: pipenv install django But, it returns this: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Scripts\pipenv.exe\__main__.py", line 7, in <module> File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1130, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\cli\options.py", line 58, in main return super().main(*args, **kwargs, windows_expand_args=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1055, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 760, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 760, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\cli\command.py", line 233, in install do_install( File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\routines\install.py", line 61, in do_install ensure_project( File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\utils\project.py", line 26, in ensure_project if project.s.PIPENV_USE_SYSTEM or project.virtualenv_exists: ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 252, in virtualenv_exists if os.path.exists(self.virtualenv_location): ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 449, in virtualenv_location self._virtualenv_location = self.get_location_for_virtualenv() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 274, in get_location_for_virtualenv return str(get_workon_home().joinpath(self.virtualenv_name)) ^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\utils\shell.py", line 195, in get_workon_home os.makedirs(expanded_path, exist_ok=True) File "<frozen os>", line 225, in makedirs PermissionError: [WinError 5] Access is denied: 'C:\\Users\\swayam\\.virtualenvs' I was trying to … -
Django 'none' values from ajax
My views: def deleteDepartement(request): object_id = request.POST.get('Id') name= request.POST.get('name') print(object_id) print(name) try: D=Department.objects.get(id=object_id) except: print("NOT FOUND") return redirect('department') JavaScript code: $.ajax({ type: 'POST', url: "{% url 'deleteDepartement' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', Id:objectId, name:'test', }, }); I got none in value in django views. When I console.log I got the id, but when i try to sent it i got none. Any suggestions please? -
Django Field comprising of other fields
enter image description here class Car(models.Model): stockid = models.AutoField(primary_key=True) galleryIndex = models.IntegerField() title = make + model + year make = models.CharField(max_length=50) model = models.CharField(max_length=200) year = models.IntegerField() price = models.IntegerField() location = models.CharField(max_length=50) mileage = models.IntegerField() transmission = models.BooleanField(default=False) engine = models.CharField(max_length=200) registration = models.CharField(max_length=200) body = models.CharField(max_length=200) color = models.CharField(max_length=200) sellerComments = models.CharField(max_length=300) I want to achieve the title field, actually i need this to find the car model! like in query i will send a string for example: "MAKE MODEL" user can either send a make a make or a model, it cant be figured out bcs theres a single search box! anyways if i have a "title field" i can use it to query data in this way " where title contains query string!" and thats the only logic i can think of! any help would be great! Query Make and Model according to a String! -
How to skip over rows causing `Integrity Error` in unique constraints?
This is a model that I have and I want to modify it so One Advisor can only have one response with status Accepted, to do that I am creating a unique constrain in class Meta: class AdvisorResponse(UUIDTimeStampedModel): chat_request = models.ForeignKey(ChatRequest, on_delete=models.CASCADE, related_name='advisor_responses', null=True) advisor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=10, choices=ADVISOR_REQUEST_STATUS, default=ADVISOR_REQUEST_STATUS_ACCEPTED) # Data field holds calculated indexed data which is for UI consumption and doesn't change over time. data = JSONField(default=dict, blank=True) class Meta: constraints = [ models.UniqueConstraint( fields=['advisor', 'status'], name='unique_advisor_accepted_response', condition=models.Q(status=ADVISOR_REQUEST_STATUS_ACCEPTED) ) ] However, there are already existing database that has duplicate Status accepted for one response and that is causing Integrity Error: psycopg2.errors.UniqueViolation: could not create unique index "unique_advisor_accepted_response" DETAIL: Key (advisor_id, status)=(11, accepted) is duplicated I don't want to delete data in prod, how should I approach this migration so constraint on previous data is not applied like skipped over and only on new data being inserted. -
Error ```Forbidden (403) CSRF verification failed. Request aborted.``` when try to login in admin
The error occurs only on the remote server. Locally everything is fine. seems to be no problem with static Didn't touch anything here: ALLOWED_HOSTS = [] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] Using: django, nginx, docker, git actions. Where is trouble? Another problem when I insert a link without an closed bracket (my-dns.com/admin) redirects me to 127.0.0.1/admin/ without port. when link is fine, trouble with csrf token -
Add a set of 'sub-forms' (probably form set) to a ModelForm
I'm making some progress in solving this. What I want to model is this: I have a model for materials, a model for projects, and an intermediary model to specify more data to the many-to-many relationship between them. The objective is to allow a project not only to have multiple materials but also to specify a quantity for each. These are my models: class Material(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.CharField(max_length=3000, blank=True) unit = models.CharField(max_length=20) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0)]) created_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='materials') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} (${self.price}/{self.unit})' class Project(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.CharField(max_length=3000, blank=True) materials = models.ManyToManyField(to=Material, through='ProjectMaterialSet', related_name='projects') created_by = models.ForeignKey(to=User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name}' class ProjectMaterialSet(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(to=Project, on_delete=models.CASCADE) material = models.ForeignKey(to=Material, on_delete=models.CASCADE) material_qty = models.PositiveIntegerField(default=1) Now, I have successfully rendered the project form containing a checkbox list of the materials (without the quantity feature), another form listing just one material as a checkbox, and a field for the quantity (a form of the ProjectMaterialSet model). Now, the part I'm struggling with is how to combine both. So far, I think what I need to do … -
Get access token from HttpOnly cookie for server side request with getServerSideProps
So, I've been working on a project using nextjs for frontend and django for backend. I'm also using HttpOnly cookies for my access and refresh tokens that I'm setting from my django backend. So, the thing is, if I send my requests on the client side by using useEffect for example, it works just fine. My django custom authenticate can read the cookie off of the request with no trouble. The problem is for when I use any server side function like getServerSideProps. I've checked and the problem is that the cookie isn't being sent with the request to the backend. I've tried to manually add the cookie to the request headers like this : export async function getServerSideProps(context) { const { req } = context console.log('accessToken >>> ', req.cookies.access); // Undefined const response = await axiosInstance.get('http://localhost:8000/api/project/projects', { headers: { "Authorization" : `Bearer ${req.cookies.access}` } }); const data = response.data; return { props: { data, }, }; } // axiosInstance export const axiosInstance = axios.create({ baseURL: "http://127.0.0.1:8000/api/", timeout: 20000, withCredentials: true, headers: { "Content-Type": "application/json", "Accept": "application/json" } }) But the problem is that the cookie I'm trying to read always gives back an undefined value. I've tried some other … -
How to redirect user in template view's get_context_data
Does anyone know how I can redirect the user to another link using the the get_context_data? The reverse lazy below is not working def get_context_data(self, **kwargs): context = super(Name, self).get_context_data(**kwargs) if self.request.user.is_student: if self.request.user != User.objects.get(id=self.kwargs['pk']): return reverse_lazy('link_name', kwargs={'pk': self.kwargs['pk']}) else: pass -
How can I reload gunicorn server using ansible?
I have a gunicorn server which run my Django website on localhost:8000. Currently I use lsof to check for pid and shutdown it using kill -9 command. Then I start gunicorn server again. - name: Find all process using port 8000 ansible.builtin.shell: "lsof -t -i:8000" register: processes_on_port - name: Stop all processes running on port 8000 ansible.builtin.shell: "kill -9 {{ item }}" with_items: "{{ processes_on_port.stdout_lines }}" ignore_errors: yes - name: Start gunicorn server community.general.gunicorn: app: "django_my_website.wsgi" chdir: /opt/my_website/django_my_website venv: /opt/my_website_venv I want to reload it without shutting down using Ansible playbook. Is there any way I can do it ? -
File is not submitting correctly, nested objects Django Models
I am trying to create a method that will send a created Model object to the server, validate it and save it. But this Model has another Model nested in it. The Model that is nested in it has an image file that also needs to be validate, but everytime I submit it says that file is not a file and not the correct encoding type. Code async function createFile(input) { let response = await fetch(input); let data = await response.blob(); let metadata = { type: 'image/jpg' }; // let name = input.substring(input.lastIndexOf('/')+1,input.length); return new File([data], input, metadata); } const updated_items = async () => { let a = props.items for (let i = 0; i < a.length; i++) { let img = await createFile(props.items[i].cover) let newimg = { "lastModified": img.lastModified, "lastModifiedDate" : img.lastModifiedDate, "name" : img.name, "size" :img.size, "type": img.type } a[i].cover = img } return a } const onAddClick = async () => { const formData = new FormData(); let items = await updated_items() // formData.append('about', about); // formData.append('name', cname); // formData.append('worn',date); // items.forEach(item => { // formData.append(`items[]`, JSON.stringify(item)); // }); for (let pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } // console.log(items) const data = … -
how to order docker compose executions?
I need to run my database in the first place, because when I do docker-compose up I got this error, because database isn't running yet: django.db.utils.OperationalError: connection to server at "db" (172.27.0.2), port 5432 failed: Connection refused test-task-web-1 | Is the server running on that host and accepting TCP/IP connections? Dockerfile: FROM python:3.11-alpine WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "backend/manage.py", "runserver"] docker-compose: version: "3.9" services: db: image: postgres:15.4-alpine expose: - "5432" environment: POSTGRES_DB: referal-api POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - ./data:/var/lib/postgresql/data web: build: context: . dockerfile: Dockerfile restart: always ports: - "8000:8000" depends_on: - db links: - db:db -
apscheduler Lost connection to my datatbase during runtime (Hosted app and database on digital ocean)
I have an app that uses apscheduler to excute jobs and the intervel of a job being excuted is 8 days. It was working fine for the first 2 weeks but on the next schdeualed run time all the jobs had the same error and from what I could tell they seem to have lost connection to the database although nothing has been changed ` Job "auto (trigger: interval[8 days, 0:00:00], next run at: 2023-08-22 23:29:16 UTC)" raised an exception Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 308, in _cursor return self._prepare_cursor(self.create_cursor(name)) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 330, in create_cursor cursor = self.connection.cursor() ^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.11/site-packages/apscheduler/executors/base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/main/automate.py", line 7, in auto client = Client.objects.get(CLIENT_ID = client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 633, in get num = len(clone) ^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 380, in self._fetch_all() File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 1881, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 91, in iter … -
Django : computationally/data intensive website
I come from the world of object programming (C++, python...) and am currently switching to web programming (django). The websites I went to build are computationally and data intensive (like complex spreadsheets with a lot of math involved). I have a hard time understanding what databases are used for in web programming and more generally understanding the architecture of web apps (or say computationally intensive websites). Here is my understanding : Databases are only doing the persistence (in a very organised way, very much like how objects are organised in memory), not for computations? If computation is required on the data (and the computation is server-side), the data is first queried by django from the DB then loaded into a python "object" data model, then the computation happens in plain python and sent to the client thanks to django's templates? Am I right? Additionally, I expect the data to be loaded at the beginning of a session. Architecturally speaking, were in django should the query of the DB and deserialisation of the data be achieved? -
Is this legitimate way of overriding the default user model
I am overriding django's default user model . I tried to link the userprofile with the CustomUser model and added a receiver which will automatically create instance of profile model when user is created based on their role from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager from django.db.models.signals import post_save # Create your models here. class CustomUser(AbstractUser): username = None email = models.EmailField(_("email"),primary_key=True,unique=True,blank=False,null=False) phone_number = models.CharField(max_length=10,null=False,blank=False) ROLE_CHOICES = ( ('ADMIN', 'ADMIN'), ('STUDENT','STUDENT'), ('TEACHER', 'TEACHER'), ('PRINCIPAL', 'PRINCIPAL'), ) role = models.CharField(choices=ROLE_CHOICES, blank=True,default='ADMIN',max_length=10) REQUIRED_FIELDS = ['phone_number','first_name','last_name'] USERNAME_FIELD = "email" objects = CustomUserManager() def __str__(self): return self.email class StudentProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) merit = models.CharField(max_length=6,blank=True,null=True) def __str__(self): return self.user.email class TeacherProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) salary = models.CharField(max_length=6,blank=True,null=True) education = models.CharField(max_length=100,blank=True,null=True) def __str__(self): return self.user.email class PrincipalProfile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) id = models.AutoField(primary_key=True,unique=True) salary = models.CharField(max_length=6,blank=True,null=True) education = models.CharField(max_length=100,blank=True,null=True) years_of_experience = models.IntegerField(null=True, blank=True) def __str__(self): return self.user.email @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.role == 'PRINCIPAL': PrincipalProfile.objects.create(user=instance) elif instance.role == 'STUDENT': StudentProfile.objects.create(user=instance) elif instance.role == 'TEACHER': TeacherProfile.objects.create(user=instance) else: pass else: print("Profile not created") As a newcomer to coding, I've crafted … -
Handling Django Migrations Folder Persistence in Azure App Service
I'm deploying a Django application on an Azure web app. As I've learned, Azure App Service is ephemeral, meaning I can't rely on files being persistent. While I've found solutions online on how to manage media files using Azure Storage, I'm unsure about how to handle other Django-specific directories, particularly the migrations folder. It seems imperative for Django to have access to this folder to conduct migrations properly. Can anyone guide me on the best approach to handle Django here? Or maybe handle azure? I'm surprised by the lack of online resources discussing best practices for this specific scenario. -
django simple JWT getting user ID from view level
I'm making a website. For the first time I decided to make an authorization with simpleJWT. Everything works fine but I don't know how can I get logged user id or just logged user object from view. @api_view(['GET']) def test(request): if request.method == 'GET': return Response({'id':request.user.id}) request.user.id return null even if I'm logged in this is my authorization from frontend export default function Login(){ const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [loggedIn, setLoggedIn] = useState(localStorage.access_token ? true : false); const submit = async e => { e.preventDefault(); const user = { email: username, password: password }; const response = await fetch("http://localhost:8000/token/", { method: "POST", headers: { "Content-Type":"application/json", }, body: JSON.stringify(user), }) const data = await response.json(); localStorage.clear(); localStorage.setItem('access_token', data.access); localStorage.setItem('refresh_token', data.refresh); setLoggedIn(true); } return( ... some form ... ) } urls from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api/', include('posts.urls')), path('token/', jwt_views.TokenObtainPairView.as_view(), name ='token_obtain_pair'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'), ] how can I get user ID from view ? -
Is there any way to recover Streamfield data that was lost due to lack of migration?
As a Wagtail newbie, I pushed changes to StreamFields in my models (i.e., adding new block types) without creating Migrations, as specified in the docs. This resulted in a large loss of user data, and unfortunately there isn't a recent database backup. If I were to go digging in a copy of the current Postgres database, would I be able to find the lost user data in the version history somehow? I'm also open to any other suggestions about how to recover the lost data, if possible. -
Django Crispy Form Doesn't Include Model ID When Using `{% crispy form %}` Tag
I have a Django crispy form that I'm using to update an object. I need to use a helper as follows: # forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, ButtonHolder, Submit class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('type', 'instructions', 'required') def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(*self.fields.keys(), css_class='form-group'), ButtonHolder( Submit('submit', 'Submit', css_class='btn-primary') ) ) ) And in my template I have the following: <form method='post' action=''> {% crispy form %} </form> My problem is that in the rendered HTML, there is no hidden field storing the ID of the Question being updated. What I expect to see is something like this: <input type="hidden" name="question-id" value="1" id="id_question-id"> This is strange. So I tried doing the following: <form method='post' action=''> {{ form | crispy }} </form> And this works. The hidden ID field is present in my HTML, and everything works perfectly. Unfortunately, this approach does not work with my form helper, which defeats the purpose of using crispy-forms. Why doesn't the ID field show up when I use the {% crispy form %} tag? -
Can't connect to MySQL server on 'localhost:3306' in dockerised Django app using docker-compose
I'm trying to build a Dockerized Django application with a MySQl database, but am unable to connect to the database when running docker-compose up My Dockerfile is: # Use the official Python image as the base image FROM python:3.10 # Set environment variables ENV PYTHONUNBUFFERED 1 # Set the working directory inside the container WORKDIR /app # Copy the requirements file and install dependencies COPY requirements.txt /app/ RUN pip install -r requirements.txt CMD ["sh", "-c", "python manage.py migrate"] # Copy the project files into the container COPY . /app/ And docker-compose.yml looks like: version: '3' services: db: image: mysql:8 ports: - "3306:3306" environment: - MYSQL_DATABASE='model_db' - MYSQL_USER='root' - MYSQL_PASSWORD='password' - MYSQL_ROOT_PASSWORD='password' - MYSQL_HOST='localhost' volumes: - /tmp/app/mysqld:/var/run/mysqld - ./db:/var/lib/mysql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db env_file: - .env I'm using a .env file to define environment variables, and it is: MYSQL_DATABASE=model_db MYSQL_USER=root MYSQL_PASSWORD=password MYSQL_ROOT_PASSWORD=password MYSQL_HOST=localhost These are then loaded to the app settings.py like this: BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() if READ_DOT_ENV_FILE := env.bool("DJANGO_READ_DOT_ENV_FILE", default=True): # OS environment variables take precedence over variables from .env env.read_env(env_file=os.path.join(BASE_DIR, '.env')) MYSQL_DATABASE = env('MYSQL_DATABASE', default=None) MYSQL_USER = env('MYSQL_USER', default=None) MYSQL_PASSWORD = env('MYSQL_PASSWORD', default=None) … -
Django rendering {% csrf_token %} as string when I set innerHTML
I have a page in which I have created a modal. Now I'm creating form in the modal that can be generated dynamically on the basis of which button is clicked. I have this JS function that sets the model content with form data. function openModal(askField, platformName) { const modal = document.getElementById("modal"); const modalContent = modal.querySelector('.modal-content'); modalContent.innerHTML = ` <h2 class="m-2 text-xl font-semibold text-center">${platformName} Authorization</h2> <form class="p-2" method="post" action="/authorize/${platformName.toLowerCase()}"> {% csrf_token %} <div class="p-3 border border-gray-500 rounded-lg"> <div class="m-2 flex justify-start space-x-2"> <label class="font-bold" for="ask_field">${titleCase(askField.replace("_", " "))}</label> <input class="border" id="ask_field" name="ask_field" required> </div> <div class="flex justify-between"> <button class="px-4 rounded-lg text-white transition ease-in-out delay-150 bg-red-600 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300" onclick="closeModal()"> Close </button> <button class="px-4 rounded-lg text-white transition ease-in-out delay-150 bg-blue-500 hover:-translate-y-1 hover:scale-110 hover:bg-indigo-500 duration-300"> Authorize </button> </div> </div> </form> `; modal.classList.remove('hidden'); } This modal works successfully. The only problem is that when this {% csrf_token %} is not actually embedded into the page but it's rendering as a string. I know as I'm adding this piece of HTML after the page is already rendered by the Django. That's why this is happening. Is there any way that I can get this working? -
Getting data for multiple objects using django checkbox
I want to get data of all objects that are selected in django admin panel using the checkbox but i can't get it right: class SalesView(View): def get(self, request, sales): sales = SaleItem.objects.all() i know i need to turn this all() function to filter to get id but just won't work! -
refar a path in root of django project from a tamplate
I have this structure: Project common Application templates common index.html static ... app1 Application ... app2 Application ... ... node_modules swiper swiper-bundle.min.css I have write this code in index.html: <link rel="stylesheet" href="../../../node_modules/swiper/swiper-bundle.min.css"> But not working and the swiper-bundle.min.css file not found. So, if I use this path href="/static/swiper-bundle.min.css" and the swiper-bundle.min.css stores in root/common/static it will works truely. How can access the swiper-bundle.min.css has located in root/node_modules/swiper/swiper-bundle.min.css ?