Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Celery - periodic_task in random time
I'm trying to run my celery task at random intervals. How can I do it the easiest way? I tried to do the task this way, but it only calls my random function once. And then he always performs at a previously random time interval. tasks.py from celery.task.schedules import crontab from celery.decorators import periodic_task import random a = random.randint(1, 5) @periodic_task(run_every=(crontab(minute='*/%s'%a))) def get_all_weather_data(): print('This is my random number %s'%a) So I changed that a new random function would be called each time. It seems to me that it works well, but it is not very effective. def random_function(): a = random.randint(1, 5) return a @periodic_task(run_every=(crontab(minute='*/%s'%random_function()))) def get_all_weather_data(): print('This is my random function') Does anyone know a better way to call a random interval of 1 to 5 minutes in which the celery task will be done? Maybe there is some built-in function that I missed in the documentation? This seems to be a fairly common problem. Any help will be appreciated. -
How to validate if a field is not blank in a form when it's set Blank = True in the model
I have a model wich is filled in different steps by different forms. Fields that are not filled in the first step need to be set Blank = True so you can submit the form. When I try to fill those fields later, the form lets the user leave them blank, which is undesirable. How can I make them mandatory in the subsecuent forms? I've tried implementing a Validation method (clean_almacen) like the one below, but it does nothing. class RecepcionForm(ModelForm): def clean_almacen(self): data = self.cleaned_data['almacen'] # Check if the field is empty. if data == '': raise ValidationError(_('¡Seleccione un almacén!')) return data def clean_usuario(self): if not self.cleaned_data['usuario_recepcion']: return User() return self.cleaned_data['usuario_recepcion'] class Meta: model = Pedido fields = ['almacen'] Also, setting the field Blank = False and null = True will make this work, but it will make mandatory to assign a value to the field when you edit the object in the admin page (which is undesirable too). This is my code: models.py class Pedido(models.Model): nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.')) referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.')) cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = … -
Django - Best way to create snapshots of objects
I am currently working on a Django 2+ project involving a blockchain, and I want to make copies of some of my object's states into that blockchain. Basically, I have a model (say "contract") that has a list of several "signature" objects. I want to make a snapshot of that contract, with the signatures. What I am basically doing is taking the contract at some point in time (when it's created for example) and building a JSON from it. My problem is: I want to update that snapshot anytime a signature is added/updated/deleted, and each time the contract is modified. The intuitive solution would be to override each "delete", "create", "update" of each of the models involved in that snapshot, and pray that all of them the are implemented right, and that I didn't forget any. But I think that this is not scalable at all, hard to debug and ton maintain. I have thought of a solution that might be more centralized: using a periodical job to get the last update date of my object, compare it to the date of my snapshot, and update the snapshot if necessary. However with that solution, I can identify changes when objects … -
Speed up queryset with aggregate in Django Orm
I'm waiting for quite long time before i get report in my project(written in Django = 2.2, python=3.7). i have complicate Model schema, and in my report i'm actually want to get users' information for particular tasks. I have find what part of my code making me wait so long and can't update it myself I've tried to change Aggregate function to annotate, but it works even longer. I've researched in Django documentation and googled for better approaches but couldn't find any good information how to modify existing code. I've also tried to add index=True to Model ,which I'm often work with when i get reports, but didn't succeed too. def make_report(self, worklogs, project, date_range_list, from_date): report = {} current_date = for d in date_range_list: report[str(d.date())] = {} for user in tasks.user.iterator(): current_user_usernames = user.get_board_usernames() #here is the problems begin **report[d.strftime('%Y-%m-%d')][user.id] = ( worklogs.filter(username__in=current_user_usernames) .filter(timestamp__range=(from_date, from_date + datetime.timedelta(days=1))) .aggregate(Sum("seconds"))["seconds__sum"] or 0 )** # each iteration takes quite long time current_date = current_date + datetime.timedelta(days=1) return report I'm waiting about 8-10 seconds for small tasks , and till couple of minutes for very big tasks. -
Django - How I can populate data in a model from another table/model in the same database?
I have a form that once is filled out, I'd like for it to cross-check the Employee # with another model's data and if the person exists, then the name would be automatically populated with the matching person once the entry is submitted. Currently I have this, but I'm not sure how to check for the number and then take the name of the person and copy it elsewhere. models.py class EmployeeWorkAreaLog(models.Model): employee_name = models.CharField(max_length=25) employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) time_out = models.DateTimeField(blank=True, help_text="Time out", null=True) def __str__(self): return self.employee_number and I have another model in the database which stores current employees with their names and ID #'s, which looks sorta like this. class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) adp_number = models.IntegerField(max_length=6) ... This is my views too, just in case. I created a function which returns the employee name from the database that has it, but I'm not sure how to use it of if there's another way to approach this. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num … -
Django: manage.py loaddata is returning 'Deserialization Error'
So when I try to load data into my models from my .json file from cmd, it is giving me this error: It seems to be a problem with the 'category_id' but I'm not sure how I go about fixing this issue. Here is my code: shop/models.py from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.TextField() products = models.ManyToManyField('Product') def get_products(self): return Product.objects.filter(category=self) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category',args=[self.id]) class Product(models.Model): name = models.TextField() description = models.TextField() stock = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=2) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.name shop/views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product from django.db.models import Count from django.contrib.auth.models import Group, User from django.core.paginator import Paginator, EmptyPage, InvalidPage def product_list(request, category_id=None): category = None products = Product.objects.all() ccat = Category.objects.annotate(num_products=Count('products')) if category_id: category = get_object_or_404(Category, id=category_id) products = products.filter(category=category) paginator = Paginator(products, 3) try: page = int(request.GET.get('page', 1)) except: page = 1 try: products = paginator.page(page) except(EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, 'products.html', {'products': products, 'countcat':ccat}) And this are the two .json files I wish to load into my database (worth noting that createcategories.json worked without issue) createcategories.json … -
How to contextualy cache class method result in Python
I have a django model which implement a method performing database queries. During an import process, This method will be called in different part of the code. I want to avoid multiple database queries because I know the result will be the same during the import process. This method would be called in many parts of the code and it would be difficult for me to do dependencies injection. I'm seeking for a way to do that using a context manager but may be it's not the best option : class OrganizationSettings(models.Model): year = models.IntegerField() @classmethod def for_year(cls, year): return cls.objects.get(year=year) class CacheOrganizationSettings(): def __init__(): # ??? pass def __enter__(self): # ??? pass def __exit__(self, type, value, traceback): # ??? pass def process(): # Somewhere in the (deep)code this is called many times : settings = OrganizationSettings.for_year(2018) # No cache used (query at each call) process() # With cache (query, one by year) with CacheOrganizationSettings(): process() -
Django query duplicated 2 times in form
I'm trying to do a signup form for my django website. There is 3 fields : Username, password and Race. With my code, the django debug toolbar tells me : (4 queries including 2 similar and 2 duplicates ) The problem is only with "Race", deleting it in the template solve the problem. How can I get rid of the duplicates, and how to only call the names ? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'race',) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) ...... views.py def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): ....... else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) signup.html <form method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.subject.errors }} .... {{ form.username }} ..... {{ form.password1 }} .... {{ form.race }} <button>Sign up</button> </form> I want the user to be able to select the race name, but with my code I'm guessing it call the whole thing with the values linked to it, when I only want the name. Thanks for the help -
Images are not shown on my heroku website. static files are loaded fine
In my website static files are loaded without problem. But media files under Training.image.url containing images are not loading. I tried looking for solution online and on this forum as well but no solution. Following are small portion of my files. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfoliodb', 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': 'localhost', 'PORT': config('DB_PORT'), } } ------------------------------------------------------- STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py file urlpatterns = [ path('admin/', admin.site.urls), path('', Trainings.views.home, name = 'homepage'), path('blog/', include('Blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to fix NoReverseMatch in django?
Here is the detail error: NoReverseMatch at /accounts/login/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username> [^/]+)/$'] Request Method: POST Request URL: http://192.168.109.138:8000/accounts/login/ Django Version: 2.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username> [^/]+)/$'] the part of views.py in users app: class UserUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ["nickname", "job_title", "introduction", "picture", "location", "personal_url", "weibo", "zhihu", "github", "linkedin"] template_name = "users/user_form.html" def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self, queryset=None): return self.request.user I can not figure out how the reverse() function work and what are the useages of args and kwargs the users\urls.py: from django.urls import path from zhuri02.users import views app_name = "users" urlpatterns = [ path("update/", views.UserUpdateView.as_view(), name="update"), path("<username>/", views.UserDetailView.as_view(), name="detail"), ] the config\urls.py urlpatterns = [ path("users/", include("zhuri02.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm not sure how to figure this error,please do help,thanks in advance. -
Delete appointments with more than 30 minutes
I have this model and I am responsible for creating a function that eliminates those appointments with "CART" status that have more than 2 hours. APPOINTMENT_STATUS_CHOICES = ( ('ACTIVA','ACTIVA'), ('CERRADA','CERRADA'), ('CARRITO','CARRITO'), ('CANCELADA','CANCELADA') ) class CitaSucursal(models.Model): fecha_cita = models.DateField(null=True, blank=True) hora_inicio = models.TimeField(null=True, blank=True) hora_final = models.TimeField(null=True, blank=True) sala = models.CharField(max_length=45,null=True, blank=False, choices=SALA_ESTUDIO_CHOICES) id_sala = models.IntegerField(null=True, blank=True) prueba = models.CharField(max_length=100,null=True, blank=False) categoria = models.CharField(max_length=45,null=True, blank=False, choices=ESTUDIO_CHOICES) notas = models.CharField(max_length=200,null=True, blank=True) estatus = models.CharField(max_length=13,null=True, blank=False, choices=APPOINTMENT_STATUS_CHOICES) id_pago = models.CharField(max_length=45,null=True, blank=True) creacion = models.DateTimeField(auto_now_add=True) # When it was create ultimaActualizacion = models.DateTimeField(auto_now=True) # When i was update Paciente = models.ForeignKey(Paciente, null=True, blank=False, on_delete=models.CASCADE) Sucursal = models.ForeignKey(Sucursal, null=True, blank=False, on_delete=models.CASCADE) -
How to scrape data from website using web-scraping and store them in DJANGO models to display them later in HTML file
I am creating a University Forum using DJANGO Framework. In one of its modules, i have to scrape data from different university websites, (data contain fee structure and program offered, etc) and then store that data in DJANGO Models and then display it in HTML.. how it is possible.this is a website link "http://nu.edu.pk/Admissions/FeeStructure" thank you -
TimeoutError when trying to send email in django
enter image description here Hello i am getting TimeoutError while trying to send mail through django . the error shows as:A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond def mail_send_view(request, id): subject = 'Subject' message = 'message' send_mail(subject, message, 'kumar943954@gmail.com', ['aditya9090400@gmail.com'],fail_silently=False) return render(request, 'blog/sharebymail.html', {'form': form, 'post': post, 'sent': sent}) -
decode csv file in utf-8 (django + pandas)
My code generates a csv file, returns it to the browser. After downloading the file, all Russian words look like: РђР ± Р ° РєР ° РЅ ... encoding as if it doesn’t work. Tell me, please, how can I solve the problem? dataCsv = data.to_csv(sep=';', header='True', decimal=',', encoding='utf-8') response = HttpResponse(dataCsv, content_type="text/csv") response['Content-Disposition'] = 'attachment; filename=data.csv' return response -
How to connect to snowflake database from Django framework
I'm new to Django and I'm trying to display the result that comes from a Snowflake database. I know that Django has multiple built-in database backend engines like: django.db.backends.postgresql and django.db.backends.mysql among the other few it supports. Unfortunately, I couldn't find a proper way of configuring a database backend engine in the settings.py My guess was to go with sqlalchemy as that's what I usually use to connect to Snowflake outside of Django but for some reason, it's not working properly. I'd appreciate any guidance on that. -
Django has exception while "collectstatic" django.core.exceptions.SuspiciousFileOperation after adding STYLESHEETS in PIPELINE
As soon as I defined 'STYLESHEET' in my PIPELINE and did run python3 manage.py collectstatic, I got the django.core.exceptions.SuspiciousFileOperation: The joined path (/) is located outside of the base path component (/opt/luciapp/apps/web/lapp-web-site/src/apps/main/frontend/static) I'm sure it's nothing to do with my STATICFILES_DIRS or the STATIC_ROOT I'm an intermediate in Django Dev and surely a noob in front-end, Please help me with this. I've attached the snippets of the error log as well as the settings snippet (website) ➜ src git:(clean_for_production) ✗ python3 manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /opt/luciapp/apps/web/lapp-web-site/public This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/usr/local/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: File "/usr/local/lib/python3.7/site-packages/pipeline/storage.py", line 26, in post_process packager.pack_stylesheets(package) File "/usr/local/lib/python3.7/site-packages/pipeline/packager.py", line 100, in pack_stylesheets … -
How to exlude fields from forms?
A have model form with a few fields. In one template I want to use all of these fields in one template and exlude a certain field in another. Is it possible not to write new form and just exclude this field in views.py? -
Django ImageField upload works locally but not on production
MY MODELS FILE from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE) description = models.CharField(max_length=100,default='') city = models.CharField(max_length=100,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) avatar = models.ImageField(upload_to='avatars/',blank=True,default='avatars/no.png') genre = models.IntegerField(choices=((1, ("Homme")), (2, ("Femme"))) ) def __str__(self): return self.user.username Locally when I fill the form, the image is saved in my file media/avatars/. But locally the image is not saved in this file and therefore it can not be displayed. -
Cannot install mysql / django on macOS 10.14.6
I'm getting an error while setting up django and MySQL in macOS. This is what I've tried so far python manage.py runserver 0:8000 ... django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? pip install mysqlclient Requirement already satisfied: mysqlclient in ./venv/lib/python3.7/site-packages (1.4.2.post1) WARNING: You are using pip version 19.3; however, version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. pip install mysql-python Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip ERROR: Command errored out with exit status 1: command: /Users/Neil/Documents/GitHub/yas/venv/bin/python3.7 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/pip-egg-info cwd: /private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.3; however, version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. pip install mysqlclient Requirement already satisfied: mysqlclient in ./venv/lib/python3.7/site-packages (1.4.2.post1) WARNING: You are using pip … -
i can't save my form in database while iam saving getting error "'bool' object has no attribute '_committed'"
hii iam new to Django so iam working on my first blog which is articals blog so i am try to save articles from the template using Django forms but while saving getting error 'bool' object has no attribute '_committed' iam searching for a solution but didn't find out any solution. please help me. Models.py: class post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=20) discription=models.CharField(default=None ,max_length=100) text = models.TextField(max_length=2000) image=models.ImageField(upload_to="blog/",default=True,null=True,blank=True) created_date = models.DateTimeField(default=timezone.now()) published_date=models.DateTimeField(blank=True , null=True) def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title forms.py: from django import forms from .models import post class post_form(forms.ModelForm): class Meta: model=post fields=[ 'title','discription','text','image' ] views.py: def post_new(request,*args,**kwargs): if request.method == 'POST': form=post_form(request.POST,request.FILES) if form.is_valid(): form.save() form=post_form() else: form = post_form() context = { 'form': form } return render(request,'blog/post_new.html',context) -
How can I make a user data if I don't get the data from the JSON response?
I'm creating a app that get information from some users, like name, email, ID number, etc. I want to get a response from a POST but in some cases i don't get the email from the users, so I need to create a parameter with this empty data. In other words I'm making a parse of the parameters of the POST and checking if all the data is good and legit, if I don't get the email from the API i want to create a parameter or maybe a empty string at least. try: if not email: errors['email'] = _(u'This data is missing.') else: validate_email(email) if email != user_data['email']: if user_data['email'] in ["", None]: user_data['email'] = email # If the email is modified, its no longer verified and I check if the user is registered with another email. if 'email_verified' in user_data: user_data['email_verified'] = False users_same_mail = User.objects.filter(email=email) if users_same_mail.exists(): # I check if the email is twice registered # I give the user another email registered in the database errors['email'] = _( u'The email is already registered.') except ValidationError as e: errors['email'] = _( u'Bad email, please enter another one.')``` What can i write to create a empty string … -
Django UpdateView doesn't Saving form, not getting any visible errors
I have a Model, ServiceVisit, and I'm using a listview to show the query results and then I have a button loading the UpdateView in a popup window to edit but the form isn't saving. I have no styling applied and it's using form.as_p and I'm not getting any validation errors that I can see. I've tried to verify that all fields are listed and all fields have a value when the form is submitted. I've looked through the docs at Django of course and searched the problem here as well to no avail. Model class ServiceVisit(models.Model): #People involved(Client, Driver, CSR) ISVERIFIED = [('0', 'Unverified'), ('1','Verified')] ISTRUE = [('0', 'False'), ('1', 'True')] client_id = models.ForeignKey('Client', on_delete=None, null=True, blank=True) customer_service_rep = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service')) remove_csr_credit = models.BooleanField(default=False) driver = models.ForeignKey('Driver', on_delete=models.CASCADE, null=True, blank=True) vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE, null=True, blank=True) #Service Info service_date = models.DateField('Date Scheduled', null=True, blank=True) first_visit = models.CharField(default='True', max_length=1, choices=ISTRUE) projected_weight = models.IntegerField(null=True, blank=True) #Using Choices here over Booleans to speed up development verified = models.CharField(default='Unverified', max_length=1, choices=ISVERIFIED) def __str__(self): return f"{self.service_date} - {self.client_id}" View class ServiceVisitEdit(UpdateView): model = ServiceVisit fields = ['client_id', 'customer_service_rep', 'remove_csr_credit', 'driver', 'vehicle', 'service_date', 'projected_weight', 'verified'] def … -
Django: postgresql trigger
I am not really good when it comes in trigger trigger thing. I just want that if the admin update the StudentsEnrollmentRecord, it will trigger the SubjectSectionTeacher and it will save in StudentsEnrolledSubject. can you guys help me solve this problem? especially in PostgreSQL Trigger This is my trigger function on PostgreSQL, CREATE OR REPLACE FUNCTION public.enrollmentrecord() RETURNS trigger LANGUAGE 'plpgsql' VOLATILE NOT LEAKPROOF AS $BODY$BEGIN INSERT INTO StudentsEnrolledSubject (Students_Enrollment_Records,Subject_Section_Teacher) SELECT a.id AS Students_Enrollment_Records, b.ID AS Subject_Section_Teacher FROM StudentsEnrollmentRecords AS a INNER JOIN SubjectSectionTeacher AS b ON a.School_Year = b.School_Year AND a.Education_Levels = b.Education_Levels AND a.Courses = b.Courses AND a.Section = b.Sections Where a.EducationLevel=b.Education_Levels AND a.Course=b.Courses AND a.Section=b.Sections AND a.Student_Users=StudentsEnrolledSubject.Students_Enrollment_Records; END; $BODY$; ALTER FUNCTION public.enrollmentrecord() OWNER TO unidadb_admin; And this is my Django model.py class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Remarks … -
Is there a shortcut to insert {%%} in Pycharm?
i would like to be able to just type lets say "%%" into my files and get "{%%}" to be typed out? How do i accomplish this in Pycharm? -
search in mulit model using django
i want search from all my model in database , so i create this search functions for do this ... but always i got ' No results for this search ' how to fix this ? view.py: def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) pcprograms_database= PCprogram.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) androidapk_database= AndroidApks.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) androidgames_database= AndroidGames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) antiruvs_database= Antivirus.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) systems_database= OpratingSystems.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) pcgames_database= PCgames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html search form : <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}"> <input id="search_box" type="text" name="q" value="{{request.GET.q}}" placeholder=" Search For ... "/> <input id="search_button" type="submit" name="submit" value="Search"/> </form> html file : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else %} <h3> No results for this search </h3> {% endif %} {% endif %} any help …