Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test, waiting for a modal
I'm trying to write a django test that clicks a button and then waits for a modal to open and check it is the right modal. I'm using selenium and firefox. This is my test class MySeleniumTests(LiveServerTestCase): #fixtures = ['user-data.json'] def setUp(self): self.admin = User.objects.create_user(username='JohnLennon', password = 'JohnLennon') self.admin.is_superuser = True self.admin.is_staff = True self.admin.save() self.researcher = User.objects.create_user(username='PaulMcCartney', password = 'PaulMcCartney') @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chromedriver_path = '/usr/local/bin/chromedriver' cls.selenium = webdriver.Chrome(chromedriver_path, chrome_options=chrome_options) cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(MySeleniumTests, cls).tearDownClass() def researcher_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/interface/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys(self.researcher.username) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(self.researcher.password) self.selenium.find_element_by_id('id_log_in').click() def test_researcher_login_to_researchUI(self): self.researcher_login() url = self.selenium.current_url.split(':')[2][5:] self.assertEqual(u'/interface/', url) def test_new_study(self): self.researcher_login() # check new study opens WebDriverWait(self.selenium, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='id_new_study']"))).click() #self.selenium.find_element_by_id("id_new_study").click() WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) self.assertEqual(u'New Study', self.selenium.find_element_by_id("modal-title")) This is the button in the html I'm trying to click <button id="id_new_study" type="button" style='width:100%;' class="btn btn-primary" onclick = "modal_form('/interface/add_study/')" >New Study</button> This is the error message I get Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/web-cdi/webcdi/researcher_UI/tests.py", line 70, in test_new_study WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) File "/home/henry/Documents/Sites/Development/web-cdi/env/lib/python3.6/site-packages/selenium/webdriver/support/wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: I know the modal does open when I'm running the application, because I can use it. I cannot get … -
Django. Create custom object without save and return like a queryset
I need create empty objects without save in data base(like a custom object for a specific conditions) and add this object to queryset. I have wtritten code: # create empty queryset queryset = MajorMinor.objects.none() major_minor = MajorMinor.objects.model dealer = User.objects.model dealer.email = 'test@gmail.com' grower = User.objects.model grower.email = 'test@gmail.com' major_minor.major = dealer major_minor.minor = grower # add my obj to queryset queryset |= major_minor return queryset but i have had an error: type object 'MajorMinor' has no attribute 'model' -
Django custom count based on ORM filter
I am trying to gather additional information based on previously filtered data, like this count(distinct batch_id) as batches, sum(files) as files The result is influenced by the previous filtering eg. .filter(batch_id__gte=165) I tried to clone the QuerySet and annotate aboves SQL .annotate( batches=Count('batch_id', distinct=True), batch_files=Sum('files') ) but this doesn't work because then the SQL is appended to the existing SELECT query Is there an easy way of getting a second query with a custom SELECT part while keeping the WHERE part? -
[Python3][Django]how to get masklen from model
the model as below to store the ip address in postgres. from django.db import models from netfields import InetAddressField, CidrAddressField, NetManager class TestModel(models.Model): client_ip = InetAddressField(default='0.0.0.0/0', store_prefix_length=True) I want to get the IP masklength directly through the model. but I can't find a attribute correspondig to postgresql inet masklen https://www.postgresql.org/docs/9.4/functions-net.html -
Django: Get model from string without app_label
I Have a Django website which uses two databases. The models for the secondary database have been added to the same models.py but with a meta class for each of them to handle the database routing. class Meta: app_label = 'database_name' managed = False db_table = 'table_name' Now I'm trying to get a model by only using a string, however every example I've seen/tried seems to require using the app_label. apps.get_model('scripts', 'model_example') Using the app name of the actual app that everything is in results in a LookupError: App 'scripts' doesn't have a 'model_example' model. apps.get_model('database_name', 'model_example') Using the app_label that the actual models have in their meta class results in a LookupError: No installed app with label 'database_name'. I also can't seem to figure out how to solve this using AppConfig or ContentType as some other posts have mentioned. To be clear: I don't have an app with the database_name, its only used for routing. I'm looking for a way to retrieve a model by using a string, get_model() functions seem to require an actually existing app. Is there any way for me to get the model or do I need structural changes? and if so, what changes? -
How to call stored mysql procedures from django
I have 2 databases in django project: Django info (default migrations) Database with info I want to display on page. To work with second database I need to inspect it and work with raw(). But can I call stored procedure passing there variable and display it? I can't understand logic. Found this for psql , but where can I work with default python db connector? In views or creating simple python script? -
Run kubectl cronjob reusing a deployment template
I have a pod with 2 containers: a django webserver, and a cloud sql proxy. I want to run a cronjob every day (some django manage.py command). Ideally, I'd like a new container to be created in one of my running pods, by copying the webserver already running there. Find pod A Copy django container from pod A Start new django container in pod A execute command in new container of pod A shut down new container of pod A From my understanding, executing a kubernetes CronJob will create a new pod of its own. That means I need to copy everything, including volumes and proxy container. I tried to do that manually (by copypasting all the pod conf from the deployment into the CronJob conf) --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: SomeName labels: environment: SomeEnv spec: replicas: 1 template: metadata: labels: app: SomeApp name: SomeName2 environment: SomeEnv spec: containers: - image: gcr.io/org/someimage:tag name: ContainerName imagePullPolicy: IfNotPresent volumeMounts: - name: app-secrets mountPath: /var/run/secrets/app readOnly: true env: - name: SECRET_KEY valueFrom: secretKeyRef: name: app-secrets key: django - image: gcr.io/cloudsql-docker/gce-proxy:1.11 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=org:zone:db=tcp:5432", "-credential_file=/secrets/cloudsql/credentials.json"] volumeMounts: - name: cloudsql-instance-credentials mountPath: /secrets/cloudsql readOnly: true - name: ssl-certs mountPath: /etc/ssl/certs - … -
How to display contents based on their category on button click in Same page in Django?
I am working on a portfolio project. where I have to categorize the projects based on their Categories. I have given buttons for each categories and I have to display each contents of individual categories on Button Clicks below them. Eg. I have 2 projects in Design category. When I click Design I should get these two projects below the button. I tried filtering of contents and successfully displayed them in other page but unable to display them in the same page. Here is my Code: Models.py class PortfolioCategory(models.Model): projectCategory = models.CharField(max_length=200) projectSummary = models.CharField(max_length=300) projectLink = models.CharField(max_length=200) class Meta: verbose_name_plural = "categories" def __str__(self): return self.projectCategory class Portfolio(models.Model): projectName = models.CharField(max_length=250) projectLink = models.CharField(max_length=50, default="") projectImage = models.ImageField(upload_to="img/Portfolio/") projectContent = models.TextField(default="") projectCategory = models.ForeignKey( PortfolioCategory, verbose_name="Category", on_delete=models.CASCADE) def __str__(self): return self.projectName Views.Py def projectLink(request, projectLink): category = [c.projectLink for c in PortfolioCategory.objects.all()] if projectLink in category: categoryItems = Portfolio.objects.filter( projectCategory__projectLink=projectLink) myProjects = categoryItems.all() return render( request, "main/home.html#projectLink", { "projects": myProjects, "navbar": navbar, } ) projectContent = Portfolio.objects.get(projectLink=projectLink) return render( request, "main/projectItem.html", { "project": projectContent, "navbar": navbar, } ) def homepage(request): return render( request=request, template_name="main/home.html", context={ "portfolios": Portfolio.objects.all, "categories": PortfolioCategory.objects.all, "navbar": navbar, "socialLinks": socialIcons, "skillset": skills, }) template <nav id="nav" … -
"<Story: title>" needs to have a value for field "id" before this many-to-many relationship can be used
I added code, so the user can connect story maximum with 2 genres, when I try to save story it brings error in title. class Story(models.Model): title = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) alias = models.CharField(max_length=255, null=True, blank=True) def save(self, *args, **kwargs): self.alias = slugify(self.title, 'ru') return super(Story, self).save(*args, **kwargs) def clean(self, *args, **kwargs): if self.genre.count() > 2: raise ValidationError('Error') super(Story, self).clean(*args, **kwargs) -
add time when we save a Timefield in django
I have a dateTime field in a model. The dateTime field named breakfast_start_time takes an input. I have to save another variable or timefield(whichever is better) named breakfast_attendence_start_time whose value should be automatically saved 15 minutes less than the breakfast_start_time. For this we use def save(self, *args, **kwargs): #do something super().save(*args, *kwargs) I am trying to do breakfast_attendence_start_time = breakfast_start_time - time(15,0) but it is giving error that class TimeField does not define '_sub_', so the '-' operator cannot be used on its instances -
Why getting duplicated log info when using django?
When try to get log . I don't know why my django project is duplicating my log message as different format.Where should I fixing this duplicate problem. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(levelname)s - %(module)s - %(message)s - %(asctime)s', }, 'json': { '()': 'sit.providers.libs.logutils.JSONFormatter' }, 'custom': { 'format': '[ %(asctime)s - %(levelname)s ] %(message)s' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'FluentHandler': { 'level': 'DEBUG', 'class': 'fluent.handler.FluentHandler', 'formatter': 'json', 'tag': 'integration' }, 'file': { 'level': 'ERROR', 'class': 'sit.providers.libs.logutils.MakeErrorFileHandler', 'formatter': 'default', 'filename': LOG_FILE_PATH }, 'update_error': { 'level': 'ERROR', 'class': 'sit.providers.libs.logutils.MakeUpdateErrorFileHandler', 'formatter': 'default', 'filename': LOG_FILE_PATH }, 'jenkins': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'custom' }, }, 'loggers': { '': { 'handlers': ['console', 'FluentHandler', 'file', 'jenkins'], 'propagate': True, 'level': 'INFO', }, 'update_error': { 'handlers': ['console', 'FluentHandler', 'update_error', 'jenkins'], 'propagate': True, 'level': 'INFO', }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, } } and ı am using logger as : logger.info("asdad") the output is : INFO - jeep - This car is not located in america. Skipping service charge. - 2019-10-04 07:32:50,662 [ 2019-10-04 07:32:50,662 - INFO ] … -
How to let Chroniker update my table in a cronjob?
I have an issue with my Postgresql database, I'm running my app in a container. I have a custom command in my Django app working minutely, when it start, my custom command check how many proxies there are and get the max ID and choose a random one. It works well, but something gone wrong after, when I check if the proxy didn't work in my script, I delete it from my database, my database accept to delete it, nothing gone wrong here. One minute after, when the command start again my command think it have the same number of proxy, when I check my database, I've got one less, so after some minutes my app choose randomly a proxy id who didn't exist. from django.db.models import Max import random def get_proxy(): max_id = Proxy.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) while True: pk = random.randint(1, max_id) proxy = Proxy.objects.filter(pk=pk).first() if proxy: return proxy When the issue append for example max_id return 680, whereas I've got only 600 id in my database. def get_proxy(): max_id = Proxy.objects.all().aggregate(max_id=Max("id"))['max_id'] print(max_id) print('max_id') while True: pk = random.randint(1, max_id) proxy = Proxy.objects.filter(pk=pk).first() if proxy: return proxy def scrapp(): url_api = "https://*************" url_objects = ******.objects.all() proxy = get_proxy() print('proxy.id') print(proxy.id) … -
Not able to insert value into database on django form submit
I have created a form that takes 2 inputs from a user and I want to add current date-time and currently logged in user when I receive user inputs in the POST method. Help me to write a view to edit the form. In the below code I am not able to assign value to blog_author. models.py (I am accepting blog_name and blog_details from user) class blogs(models.Model): blog_name = models.CharField(max_length=100,blank=False,null=False) blog_details = models.TextField(blank=False,null=False) blog_author = models.CharField(max_length=100,blank=True,null=True) blog_created_at = models.DateTimeField(auto_now=True) forms.py #with only two fields class blogForm(forms.ModelForm): class Meta: model = blogs fields = ('blog_name','blog_details') views.py #validation of form def create_blog(request): if request.method == 'POST': form = blogForm(request.POST) if form.is_valid(): form.save(commit=False) form.cleaned_data['blog_author'] = request.user form.save() form = blogForm() context = {"form":form} return render(request,'create_blog.html',context) -
getting (" placeholder ") input attribute in django
I want to get my placeholder input attribute, when a user submit the form. How can it be done in django framework? for example, I want it to be done like this: def get_attr(request): plh = request.POST.get('placeholder') I know that the code above isn't correct, because the POST method doesn't have that attribute. So, what can I do? -
Retrieve query from django ORM
I created a Company in my django app, two or more person can login with the same company. I want to show the data of one user of the company to the other user of the company. To simplify: If user1 of a company creates an object, then it should be visible to all the users of that company Models.py class User(AbstractUser): is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) def __str__ (self): return self.company_name class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='comapany_owner') def __str__ (self): return self.user.username class Product(models.Model): product_name = models.CharField(max_length=255, default=0) product_priceperunit = models.IntegerField(default=0) product_owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='product_owner') Views.py @method_decorator([login_required, employee_required], name='dispatch') class ProductsTableView(ListView): model = Product context_object_name = 'product' template_name = 'packsapp/employee/employeeProductsTable.html' def get_queryset (self): queryset = Product.objects.filter(product_owner=self.request.user.employee) return queryset Here I am extracting the data by employee. How can I modify the query to give the data of all the employee of the same company ?? -
How to remove default value '0' in django forms using css only
I'm making django forms which requires a default value while making migrations into it but I want to show this :"--------" by default, not 0 using css only: my django form looks like this: <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </form> </div> </div> In this img, Instead of showing 0 I want "------", but must be done only with css. -
get_user(uid).email returns None if user is logged in by facebook in firebase_admin django
Code: import firebase_admin from firebase_admin import auth from firebase_admin import credentials from firebase_admin.auth import get_user cred = credentials.Certificate("cred.json") firebase_admin.initialize_app(cred) verified = auth.verify_id_token(id_token=token) print(get_user(verified["uid"]).email) output of this code will be None if user logged in with facebook, but if user is logged in with google then it will return email of user -
Django: Override user queryset to filter out admin/staff users from the public?
I want to filter the user manager self.get_queryset() method in such a way that users on the client application don't see admin and staff users when searching for or viewing other accounts. The issue I'm running into is I am unable to login with my auth system if I override get_queryset entirely. My current setup is: class AccountManager(BaseUserManager): def get_public_queryset(self): return self.get_queryset().filter(active=True, verified=True, admin=False, staff=False) Using this design works fine if I define various sorting methods in the manager (because I can simply call that method), but it seems as though there should be a better way to do this. Any ideas? -
How to Delete compete table from django sqlite database using django function in terminal?
I have written a code for my project, for that I have created some tables in Django SQLite database server. Now I want don't want table, therefore I want to remove/delete the complete table from database. Is there any way to delete table directly from the single line of code from terminal of IDE? I have tried using Django-admin from that I have use 'django-admin flush' and 'django-admin sqlflush' I am confuse what to use and what not to -
How To Render Two or More Bokeh Plots In HTML with Div and Script Tag? In Django
I want To Plot Two or More Graph in HTML using Div and script Tag , But It Plots Only last one. Am working on Django plot code..... script , divi = components(plot) plot1 = figure() plot1.circle([1,2], [3,4]) script , pie = components(plot1) return render(request,'result.html',{'company':fetch,'tabcontent':temp,'pie':pie,'last_20':last_20f,'divi':divi,'script':script}) some code... <div class="graph1"> {{divi | safe}} </div> <div class="last_20"> {{last_20|safe}} </div> <div class="pie_area"> {{pie | safe}} </div> -
html file urls is not accessible in django
register.html is not accessible on 'register/' url tried changing url to '' and webpage is accessible but not on 'register/' projects urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('login/',include('login.urls')), path('admin/', admin.site.urls), ] apps urls.py from django.urls import path from . import views urlpatterns = [ path('',views.indexView, name = "home"), path('dashboard/', views.dashboardView, name="dashboard"), #path('login/',), path('register/',views.registerView, name="register_url"), #path('logout/',), ] views.py from django.shortcuts import render def indexView(request): return render(request,'index.html') def dashboardView(request): return render(request,'dashboard.html') def registerView(request): return render(request,'register.html') templates/register.html -
#[Errno 2] No such file or directory
So, here what I am doing from the below link: https://django-microsoft-auth.readthedocs.io/en/latest/installation.html#from-sources I am trying to follow all the steps mention in the blog for the installation of django_microsoft_auth. Step-1 i.e. "pip install django_microsoft_auth" # is working Step-2 i.e. "git clone git://github.com/AngellusMortis/django_microsoft_auth" # is also working Step-3 i.e. "python setup.py install" # is giving me the below error. C:\Users\vtinkhed\AppData\Local\Programs\Python\Python37\python.exe: can't open file 'setup.py': [Errno 2] No such file or directory I don't know how to help. Could anybody help me out here? Thanks in advance -
500 internal server error during deployment of django project in elastic beanstalk
I am trying to deploy my django project in AWS elastic beanstalk. The project is deployed fine but I am getting a 500 internal server error when I go to the url after deployment. I got the following error from error log: error log mod_wsgi (pid=29607): Target WSGI script '/opt/python/current/app/DJ/wsgi.py' cannot be loaded as Python module. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: DJ/wsgi.py StaticFiles: /static/=static/ How can I solve this? -
Defining functions inside of views
I am attempting to create a job board website and upon entering a zip code in a form, that zip code is passed to a search_results view (as zip_code). In this view I need to 1. Get the surrounding zip codes (with a certain mile radius) 2. Get objects in db that match those zip codes. I have step one complete and have not implemented step two yet (actual code not that important to question): from uszipcode import Zipcode, SearchEngine def search_results(request, zip_code): zip_codes = [] search = SearchEngine(simple_zipcode=True) # create SearchEngine object zip_code = search.by_zipcode(zip_code) #create Zipcode object? latitude = zip_code.lat longitude = zip_code.lng result = search.by_coordinates(latitude, longitude, radius = 5, returns = 5) for item in result: zip_codes.append(item.zipcode) # code that will return matching objects My question is can you define functions inside of a view in Django, like such: def search_results(request, zip_code): zip_codes = getSurroundingZipCodes(zip_code) results = getJobsInArea(zip_codes) return render(request, 'results.html', {'results: results}) def getSurroundingZipCodes(zip_code): # logic for this function def getJobsInArea(zip_codes): # logic for this function This is something I haven't seen in any tutorials so I feel like the answer is no, but I'm not sure why? -
Define max relation in ManyToManyField
Story model has a ManyToMany relationship with Genre model. I want to be able set maximum 2 genres to one story. How to do that? P.S. using serilaizers, viewsets and I am used forwardfunc in migrations to provide default genres in DB class Story(models.Model): ... genre = models.ManyToManyField(Genre) class Genre(models.Model): name = models.CharField(max_length=255)