Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the size of a Django form label
I have the following form: forms.py: from django.forms import ModelForm, HiddenInput, CharField from django.core.exceptions import ValidationError import re from django import forms from cal.models import Event from project.models import Project class EventForm(ModelForm): def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) class Meta: model = Event widgets = { 'event_type': forms.Select( attrs={ 'size': '4', 'style': 'font-size:13px;' } ), } labels = { 'equipments': 'Equipment', 'event_type': 'Type', } fields = '__all__' And in my template.html I render the content of the form like this: {% bootstrap_field event_form.title layout='horizontal' size='small' %} {% bootstrap_field event_form.description layout='horizontal' size='small' %} {% bootstrap_field event_form.event_type layout='horizontal' size='small' %} I would like the label font size to be 13px; Apparently 'style': 'font-size:13px;' works only for the content of the field, not for the label. Is there a way to add styles only to label or label and field (both)? I have been reading the documentation here but it is not clear to me how to change the style, it seems like only classes can be changed...? Any help will be highly appreciated -
how to run multiple postgresql queries in github actions
I'm writing python code test on github actions and i deined workflow. but now, i don't know how to run multiple queries to build DB, user, GRANT etc... . here is my workflow: name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest services: postgres: image: postgres:latest env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres POSTGRES_PORT: 5432 ports: - 5432:5432 # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - name: Install PostgreSQL client run: | apt-get update apt-get install --yes postgresql-client - name: Query database run: psql -h postgres -d postgres_db -U postgres_user -c "SELECT 'CREATE DATABASE redteam_toolkit_db' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'redteam_toolkit_db');" run: psql -h postgres -d postgres_db -U postgres_user -c "CREATE ROLE redteamuser with SUPERUSER CREATEDB LOGIN ENCRYPTED PASSWORD '147r258r';" run: psql -h postgres -d postgres_db -U postgres_user -c "GRANT ALL PRIVILEGES ON DATABASE redteam_toolkit_db TO redteamuser;" run: psql -h postgres -d postgres_db -U postgres_user -c "ALTER DATABASE redteam_toolkit_db OWNER TO redteamuser;" env: PGPASSWORD: postgres # https://www.hacksoft.io/blog/github-actions-in-action-setting-up-django-and-postgres#resources - run: sudo apt-get install libpq-dev - run: pip install --upgrade pip wheel - run: pip install bandit black … -
How can I fetch multiple data from API calls in React js?
I used django as backend and react as frontend. I am able to call the api and show the product details but in my serializer i have related product too. I send related product response from my serializer. I want to show related product after the product details section. How can I call the object?? #this is my serializer class ProductWithRelatedSerializer(ProductSerializer): related = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_related(self, obj): related = Product.objects.filter( category_id=obj.category_id ).exclude(_id=obj.pk).order_by('?').select_related('user')[:4] ps = ProductSerializer(related, many=True) return ps.data this is my product view @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductWithRelatedSerializer(product, many=False) return Response(serializer.data) in my frontend reducer export const productDetailsReducer = (state = { product: {}}, action) => { switch (action.type) { case PRODUCT_DETAILS_REQUEST: return { loading: true, ...state } case PRODUCT_DETAILS_SUCCESS: return { loading: false, product: action.payload } case PRODUCT_DETAILS_FAIL: return { loading: false, error: action.payload } default: return state } } this is my action export const listProductDetails = (id) => async (dispatch) => { try { dispatch({ type: PRODUCT_DETAILS_REQUEST }) const { data } = await axios.get(`/api/products/${id}`) dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data }) }catch(error){ dispatch({ type: PRODUCT_DETAILS_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) … -
How to run a function in background in django python only when it is called?
I have created an email functionality which will send access token to the user for verification. This process takes little time to execute. So, I want to push this function in background and notify the user with the message "The access token would be mailed to your email id. Please check you email". This is to keep user updated rather than him waiting for the access token notification once the whole task is completed. I don't want to schedule as it is not required here and Django's background_task module won't help I suppose. What could be the way-out? -
How to clear a airflow connection table, it is possible to delete a single connection with conn id
To delete a single connection: airlfow connections delete conn id how to delete the whole connections.? -
How to install Node Packages for an Elastic Beanstalk Python 3.7 Project Running on 64bit Amazon Linux 2?
I am using a Django package named django-pipeline to compress js and css files. When I deploy my project, I run Django's collectstatic command, from .ebextensions folder: 01_django.config: container_commands: ... 07_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" The problem is, django-pipeline uses compressor libraries that require Node. I have copied two libraries (cssmin and terser) from my node_modules directory locally to my static directory. static |_vendor |___|.bin |_____|cssmin |_____|cssmin.cmd |_____|terser |_____|terser.cmd Secondly, I have the following setin on the Pipeline to tell the pipeline where the binaries exist: PIPELINE_CONFIG.update({ 'CSSMIN_BINARY': os.path.join(BASE_DIR, "static", "vendor", ".bin", "cssmin"), 'TERSER_BINARY': os.path.join(BASE_DIR, "static", "vendor", ".bin", "terser"), }) The Error 2021-09-14 05:00:58,513 P4080 [INFO] ============================================================ 2021-09-14 05:00:58,513 P4080 [INFO] Command 07_collectstatic 2021-09-14 05:00:59,502 P4080 [INFO] -----------------------Command Output----------------------- 2021-09-14 05:00:59,503 P4080 [INFO] Traceback (most recent call last): 2021-09-14 05:00:59,503 P4080 [INFO] File "manage.py", line 21, in <module> 2021-09-14 05:00:59,503 P4080 [INFO] main() 2021-09-14 05:00:59,503 P4080 [INFO] File "manage.py", line 17, in main 2021-09-14 05:00:59,503 P4080 [INFO] execute_from_command_line(sys.argv) 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line 2021-09-14 05:00:59,503 P4080 [INFO] utility.execute() 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute 2021-09-14 05:00:59,503 P4080 [INFO] self.fetch_command(subcommand).run_from_argv(self.argv) 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/base.py", line 354, … -
Legacy Apache 2.2.22 SSL Config with Django & Elasticsearch on Ubuntu 12.04
I have a legacy linux cluster based on Ubuntu 12.04 that hosts a django app on apache 2.2.22 (new system is replacing it, this is being maintained only). I've been asked to secure a website (internal facing only, not public) with some SSL keys that have been provided. I've created a symlink in /etc/apache2/conf.d to the config file below. I've been reviewing various old discussions similar to this setup. I've finally been able to get the apache service to start but the website now gives a 500 internal error on port 443. Any insights and insights are appreciated. This is still a bit new to me. Here's the config file (sorry it's a bit messy as I've been debugging) <VirtualHost *:443> #ServerName www.example.com #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine On # Set the path to SSL certificate #SSLCertificateFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2-chain.pem SSLCertificateFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2.crt SSLCertificateKeyFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2.key #Include conf-available/serve-cgi-bin.conf ProxyRequests Off ProxyPreserveHost On #Blocks reverse proxy ports /logs /logs_1 /logs_2 and /elasticsearch #match sub strings /logs* and /elasticsearch <Location ~ "/(logs|logs_1|logs_2|elasticsearch)"> Order deny,allow Deny from all AuthType Basic AuthName "Password Required" AuthBasicProvider file AuthUserFile /etc/apache2/elasticsearch-passfile Require valid-user Satisfy any </Location> #<Location /guacamole/> # Order allow,deny # Allow from all # … -
How to duplicate queryset output
When the test row satisfies both conditions 1 and 2, is there a way to print the query set twice? I've searched a lot about solutions, but only the method to distinct() duplicate querysets is shown, and there is no way to print duplicate querysets more than once. condition_1 = Student.objects.filter(Q(register_date__gte=from_date) & Q(register_date__lte=to_date)) condition_2 = Student.objects.filter(Q(eating_date__gte=from_date) & Q(eating_date__lte=to_date)) gap = ETC.objects.filter(Q(id__in=condition_1)) | Q(id__in=gap_condition_2))\ .annotate(total_gap=('create_date', filter=Q(id__in=condition_1.values('id')) + 'create_date', filter=Q(id__in=condition_2.values('id'))) -
Error loading mysqldb module in django after mysqlclient's installed
I suddenly found this issue with myssql + django in my lambdas. I used to have this snippet of code in my init and it used to work fine import pymysql pymysql.install_as_MySQLdb() Now I'm getting this error mysqlclient 1.4.0 or newer is required; you have 0.10.1.. Lambda request id: 9db6c25b-09d5-4721-8942-3a3b655ae9ba ok no problem I changed it to use mysqlclient but now I’m running into this issue Error loading MySQLdb module. Did you install mysqlclient?. Do I have to install it and do anything extra in my init file with mysqlclient? -
How to prefetch_related() for GenericForeignKeys?
I have a List that consists of ListItems. These ListItems then point towards either a ParentItem or a ChildItem model via a GenericForeignKey: # models.py class List(models.Model): title = models.CharField() class ListItem(models.Model): list = models.ForeignKey(List, related_name="list_items") order = models.PositiveSmallIntegerField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class ParentItem(models.Model): parent_title = models.CharField() class ChildItem(models.Model): child_title = models.CharField() parent = models.ForeignKey(ParentItem, related_name="child") I want to display a list of all my Lists with their ListItems and respective ItemA/ItemB data using ListSerializer: # serializers.py class ParentItemSerializer(serializers.ModelSerializer): class Meta: model = ParentItem fields = ["parent_title"] class ChildItemSerializer(serializers.ModelSerializer): parent = ParentItemSerializer() class Meta: model = ChildItem fields = ["child_title", "parent"] class ListItemSerializer(serializers.ModelSerializer): contents = serializers.SerializerMethodField() class Meta: model = ListItem fields = ["contents"] def get_contents(self, obj): item = obj.content_object type = item.__class__.__name__ if type == "ParentItem": return ParentItemSerializer(item).data elif type == "ChildItem": return ChildItemSerializer(item).data class ListSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() class Meta: model = List fields = ["title", "items"] def get_items(self, obj): return ListItemSerializer(obj.list_items, many=True).data How can I optimize my List queryset to prefetch these GenericForeignKey relationships? # views.py class ListViewSet(viewset.ModelViewSet): queryset = List.objects.all() serializer_class = ListSerializer List.objects.all().prefetch_related("list_items") works but the following does not seem to work: List.objects.all().prefetch_related( "list_items", "list_items__content_object", "list_items__content_object__parent_title", "list_items__content_object__child_title", "list_items__content_object__parent", … -
Django Sitemap for multiple domain and same site
I have a Django website with a domain www.example.com hosted on a VPS. The same Website can be accessed from different domains like www.example.xyz and www.example.one I already made a sitemap for www.example.com which is working well. Using Django contrib sitemap function. But now the problem is how to generate the sitemap for www.example.xyz and www.example.one. Sitemap from www.example.xyz and www.example.one shows me a link to www.example.com -
404 Not Found nginx/1.18.0 (Ubuntu) in django application on ec2
I was able to deploy my first django application on EC2 ubuntu 20.04 through the help of this community. After deployment, I'm not able to assess all the pages on the browser but in development all the pages are being displayed. I don't know where to start debugging because every page is displaying 404 Not Found nginx/1.18.0 on the browser. The gunicorn is running properly guni:gunicorn RUNNING pid 121305, uptime 0:54:04.. The content of /etc/nginx/sites-available/default is server { listen 80 default_server; listen [::]:80 default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name ip-address; Please how do I go about this because I know little about nginx -
Django media files get 403 forbidden
I have an app running on a Digital Ocean Droplet. I'm using Ubuntu, Nginx and Gunicorn The admin can upload media files, the upload is working fine. The problem is that when a user visits the site, the media files that the admin uploaded are not displayed due to a 403 (forbidden) error. -
Django Url for default image leads to 404
Currently working on a Django project with two Apps; projects and users. Both a user and a project can have an image; a user has a profile picture and a project has a featured image. If no image is uploaded a default image is used. Here is my problem What I want: A default image to show if no image is uploaded What I get: An incorrect link for the default profile image resulting in a 404 error (the default project image link works just fine) What I've tried: Reading old stack overflow threads, Django docs and googling it. From what I can tell it is not an incorrect media directory, a hard coded url, a jinja formatting error or a misspelled variable. The issues seems to be with the profile image url. From the top: I have my media urls/dirs configured for both local development and for production: In settings.py: MEDIA_URL = '/img/' ... MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') In my-django-project/urls.py: imports... urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('projects/', include('projects.urls')), path('profiles/', include('users.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My static directory looks like this: css/ js/ img/--|-featured_images/ |-profile_images/ | default.jpeg (this is the default project … -
How can I filter This in django?
I am working on a Django project (like LMS) and I want to filter Lectures by Subject in the template, I do it once but now I forgot how to do it. How can I do this?! I want to filter it by foreign-key Subject in Lecture Here is my models.py from django.db import models from django.utils.text import slugify # Create your models here. class Subject(models.Model): Title = models.CharField(max_length=150) Pic = models.ImageField(upload_to='media/') Test = models.CharField(max_length=300, null=True, blank=True) Slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.Slug = slugify(self.Title, allow_unicode=True) super(Subject, self).save(*args, **kwargs) def __str__(self): return self.Title class Lecture(models.Model): Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) Title = models.CharField(max_length=150) Video = models.CharField(max_length=300) More_Info = models.TextField() Audio_Lecture = models.CharField(max_length=300) Lecture_Files = models.CharField(max_length=300) Sheet = models.CharField(max_length=300) Slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.Slug = slugify(self.Title, allow_unicode=True) super(Lecture, self).save(*args, **kwargs) def __str__(self): return self.Title and here is my views.py from Diploma.models import Lecture, Subject from django.shortcuts import render # Create your views here. def Diploma(request): return render(request, 'Diploma/diploma.html', context={ 'sub' : Subject.objects.all(), }) def Diploma_Subject(request, slug): subject_Lecture = Subject.objects.all() return render(request, 'Diploma/subject.html', context={ 'subj' : subject_Lecture, 'lect' : Lecture.objects.filter(I do not know what I should write here) }) -
How do you configure your settings.py file to upload files to Amazon S3 database instead of local folders?
I have an issue with a Django/Python project currently where I can't seem to upload pictures to the amazon s3 database I have set up when making a new recipe for my cookbook app. The recipe will be created, however the picture file does not send to the S3 db and instead is sent to a local folder in my app folder instead. Would anyone know what I am doing wrong? class Recipe(models.Model): id = models.AutoField(auto_created=True, primary_key=True, verbose_name='title') title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True) image = models.ImageField(null=True, blank=True) serving_size = models.CharField(max_length=10, null=True, blank=True) prep_time = models.CharField(max_length=30, blank=True) cook_time = models.CharField(max_length=30, blank=True) ingredients = models.TextField(blank=True) directions = models.TextField(blank=True) class AddRecipeForm(ModelForm): class Meta: model = Recipe fields = '__all__' exclude = ['id', 'author'] from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<secret key here>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['<heroku app url here>', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
How to Activate Venv with venv/bin Folder Missing (Django and PyCharm on Ubuntu OS)
I have a Django project I've been working on for awhile and don't remember exactly how it started. It's possible I may have started it on Windows and transferred it over to my laptop running Ubuntu, but I can't say for sure. Looking at my project directory, I can't find the bin folder to activate my venv. I have the following: projectname/venv ls within venv: include, lib, pyvenv.cfg The confusing part is, I have been working on the site this way without issue for several months. Since it's within PyCharm the venv always activated automatically, until now. Terminal settings are still correct. But, I recently ran a different script through PyCharm and can't get back into the venv automatically or manually for this django project. It seems like I also have a second venv via: projectname/sitename/django/bin/activate When activating that venv I get a module not found error (crispy_forms) when trying to run the site. So that's not the environment I was using when building the site and installing packages/modules. My terminal always had (venv) It's possible I started the project on Ubuntu, I really don't remember. But, if that's the case I'm not sure why the bin folder would be … -
How to filter in Django-graphene?
I use graphene-Django to build a GraphQL API. I have successfully created this API, but I can't pass an argument to filter my response. I want to filter with the forging key from my model. model.py: class TodoList(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) date = models.DateField(auto_now=True) text = models.TextField() schema.py: class TodoView(DjangoObjectType): class Meta: model = TodoList fields = ('id', 'title', 'date', 'text') class UserType(DjangoObjectType): class Meta: model = User class TodoQuery(graphene.ObjectType): todoList = DjangoListField(TodoView) def resolve_all_todo(root, info): return TodoList.objects.filter(userId=2) But when I do filter it show all object in the result When I send this request: { todoList { id title date text } } I've got this response: { "data": { "todoList": [ { "id": "1", "title": "test", "date": "2021-09-13", "text": "test todo" }, { "id": "2", "title": "test2", "date": "2021-09-13", "text": "test2" }, { "id": "3", "title": "admin2 test", "date": "2021-09-13", "text": "admin2 test" }, { "id": "4", "title": "admin2 test2", "date": "2021-09-14", "text": "admin2 test2" } ] } } What I have missed? Or maybe I do something wrong? -
ModuleNotFoundError: No module named 'cvsbehaviour' AWS Elastic Beanstalk Django
I have spent way to long on this and been looking everywhere but cant seem to find the cause of my issue. I am trying to deploy a Django app on my ElasticBeanstalk via the web panel and the app is not working once deployed, the health is Severe and 100.0 % of the requests are failing with HTTP 5xx. From the logs, the error I see is the following: web.stdout.log Sep 14 00:47:05 ip-172-31-5-163 web: Traceback (most recent call last): Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Sep 14 00:47:05 ip-172-31-5-163 web: worker.init_process() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Sep 14 00:47:05 ip-172-31-5-163 web: super().init_process() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Sep 14 00:47:05 ip-172-31-5-163 web: self.load_wsgi() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Sep 14 00:47:05 ip-172-31-5-163 web: self.wsgi = self.app.wsgi() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Sep 14 00:47:05 ip-172-31-5-163 web: self.callable = self.load() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Sep 14 00:47:05 ip-172-31-5-163 web: return self.load_wsgiapp() Sep 14 00:47:05 ip-172-31-5-163 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Sep … -
Django - Static Images are not rendering from JavaScript file
On my Django project, I keep receiving a not found error for a few images. When running the project without Django (using live server), everything works fine. I have loaded static at the beginning of the html document and added all of the correct static tags. I believe it has something to do with my JavaScript File (where the image is used). For Example the html code where it pulls the JavaScript file <script src="{% static '/js/project.js'%}"></script> And the JavaScript File (project.js) const projects = [ { title: "Discord App", cardImage: "/images/project-page/download.png", description: "A Discord app.", tagimg: "https://cdn.iconscout.com/icon/free/png-512/react-1-282599.png", Previewlink: "", }, ]; I have a few images that are not on the JS file (only html) that work fine. Was wondering if anyone ran into the same problem and could help me out. Let me know if you need more information. -
save image in django template
I know that this question have been asked many times and I already checked many solutions but can not find an explanation to the weird behavior of saving form in this case as in production saving image is working on my pc and not in my colleagues, in local as well it is working if I change the position of the form save (more below, if more up it does not work) here the related forms to the template I am working with: class ProfilePageTitleForm(ModelForm): class Meta: model = ProfilePage fields = [ "title", ] class ProfilePageDetailsForm(ModelForm): intro = forms.CharField( required=True, widget=forms.Textarea( attrs={ "class": "max-w-md w-full bg-gray-100 border border-gray-200 " "rounded-lg text-base outline-none focus:border-blue-600 p-4" } ), label=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) class Meta: model = ProfilePage fields = [ "avatar", "school", "location", "intro", ] here they are separated as I used the title in another template separately related views @login_required def profile_details(request: HttpRequest, pk: int = None) -> HttpResponse: profile = ProfilePage.objects.get(pk=pk) user = profile.user titleprofilepage_form = ProfilePageTitleForm(instance=profile) profilepage_form = ProfilePageDetailsForm(instance=profile) if user == request.user or request.user.has_perm("userprofile.manager_permissions"): if request.method == "POST": profilepage_form = ProfilePageDetailsForm( request.POST, request.FILES, instance=profile ) titleprofilepage_form = ProfilePageTitleForm(request.POST, instance=profile) if ( … -
Django form submit without refreshing
thanks in advance. I know this has been asked a few times. But after reading the previous questions, reading and understanding JSON and AJAX forms tutorials, I still can't find a way to not having the website refreshed after submitting a form. I would really appreciate it if any of you with a higher knowledge of JavaScript is able to give a hand. This is a newsletter at the bottom part of the Home page that just asks for a name and an email and it keeps the information in the database, it works perfect and I just would like to reply to the confirmation message without refreshing, because it replies to a message but the user has to go to the bottom, of the page again to see it which is not practical at all. The HTML is <div id="contact_form"> <div class="Newsletter"> <form id="form" enctype="multipart/form-data" method="POST" action="" style="text-align: left;"> {% csrf_token %} <div class="fields"> <div class="fields"> <label for="name" id="name_label">Name</label> <input type="text" name="name" minlength="3" placeholder="e.g. John Smith" id="name" required> </div> <div class="fields"> <label for="email" id="email_label">Email</label> <input type="email" name="email" placeholder="e.g. john@example.com" id="email" required> </div> </div> <div class="submit"> <button type='submit' id="submit" >Subscribe</button> </div> {% include 'messages.html' %} </form> </div> </div> The index … -
Django set request.GET, i.e. set url args server side for a GET
When a user GETs a form, I would like to change the url query parameters e.g. if they request: /foo/bar/1/ I would like to reply with /foo/bar/1/?caz=7, without a redirect. I tried some answers on SO, but the browser always shows the same url, i.e. /foo/bar/1/ The recommend ways of changing request.GET: request.GET = request.GET.copy() request.GET['caz'] = 7 I imagine I am changing the request, and not the response. I looked at the response docs and don't see anyway there either. I could have a hidden widget or session middle but I am trying to avoid that. -
Can I use django orm with a database that was not set up with django
I have a database that I set up manually using raw sql and alembic. I want to now use this database in a Django app. Will the Django ORM work as expected with this DB? Would I have to set up all the models? Thanks. -
How to run a django test on an empty database outside of the test runner?
Our database accepts user-submitted load files, and for the time being, our admins are going to load the submitted files manually to resolve data issues. There are 2 types of files. For the second file to load successfully, the first file must load successfully. Since we are going to handle this ourselves, I'm writing a data validation page that does a load of the first file in debug mode so that the user can resolve simple things like unique fields and controlled vocabulary issues. But in order for me to test the second file, I need to temporarily load that first file. I decided to do this by creating a TestCase class that is not a part of our unit test suite. (Maybe there's a better way to do this than the strategy I've selected - so I'm open to suggestions.) When I run the tests from the validation view in views.py, the tests work and the data does not persist in the database - however, I'm not getting a clean/empty test database to work from. In order for this code to be guaranteed to work, I need to figure out how to create a fresh empty copy of a …