Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
My functions are not working in my django project
I'm currently trying to return data in json or api view format with my following text fields (email, country and phone number), However I also have 2 validation functions to validate the value in the email and phone number fields which require the get() method and also using it to pass the text as a argument. I am not sure if the 2 validation functions are working or not as when I entered an invalid email, it is still accepted as a valid data. Please tell me what I am doing incorrectly and what changes should be made to my current code. /* serializers.py */ import re import phonenumbers from rest_framework import serializers from .models import validation from phonenumbers import carrier from validate_email import validate_email class validationSerializer(serializers.ModelSerializer): class Meta: model = validation fields = '__all__' def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise serializers.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < 3: raise serializers.ValidationError( "Number cannot be more than 15 or less than 3") if not phonenumbers.is_valid_number(z): raise serializers.ValidationError( "Number not correct format or non-existent") … -
How to update instance's particle attribute using Django Modelseirallizer?
I want to update instance's attribute using Django Modelseriallizer. I want to change only 'tel' attribute in 'Activity' model. but my code is not working. this is model class Activity(models.Model): num = models.AutoField(primary_key=True) #번호 name = models.CharField(max_length=100, blank=True, null=True) eventStartDate = models.CharField(max_length=100, blank=True, null=True) eventEndDate = models.CharField(max_length=100, blank=True, null=True) eventTime = models.TextField(max_length=1000, blank=True, null=True) eventPlace = models.TextField(max_length=1000, blank=True, null=True) discription = models.TextField(max_length=1000, blank=True, null=True) longitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) latitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) tel = models.CharField(max_length=255, blank=True, null=True) img = models.CharField(max_length=255, blank=True, null=True) grade = models.IntegerField(default=0,blank=True, null=True) this is view class ActivityList(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): data = Activity.objects.all() serializer = ActivitySerializer(data, many=True) return Response({"ActivityList":serializer.data}) this is serializer class ActivitySerializer(serializers.ModelSerializer): tel = serializers.CharField() def update(self, instance, validated_data): instance.tel = 'new tel number' instance.save() return instance class Meta: model = Activity fields = ('num', 'name', 'eventStartDate', 'eventEndDate', 'eventTime', 'eventPlace', 'discription', 'longitude', 'latitude', 'tel', 'img', 'grade') # fields = '__all__' -
How to display error message in Django template after HttpRedirect from another view?
I'm creating a simple CRUD application without using the admin page of Django. I only have one template, index.html that displays all the list of student information. I have two views below, one is for displaying only when the user visited the index page. The other view is executed when a user in the index page clicks a submit button for registering a new student (via POST) then redirects to the index view again. I want to display an error message if the student already exists in the database (by using student number). My problem is how can I pass the error message in the index.html template after the HttpRedirect. Or am I doing it the wrong way? def index(request): studentList = Student.objects.all() return render(request, "crud/index.html", {"student_list": studentList}) def addStudent(request): data = request.POST # print(data) if data: try: newStudent = Student.objects.get(student_number=data['student_number']) return HttpResponseRedirect(reverse("crud:index")) except Student.DoesNotExist: newStudent = Student(student_number=data['student_number'], first_name=data['first_name'], last_name=data['last_name'], age=data['age'], sex=data['sex'], email=data['email'] ) newStudent.save() return HttpResponseRedirect(reverse("crud:index")) -
I had an html comment in a Django template, and it was causing a server error when DEBUG=False, why?
Previously I had a favicon.png, I deleted the favicon.png file. This did not create any issues until I switched from DEBUG = True to DEBUG = False in my settings.py file. And I got a 500 server error. To diagnose the issue I added DEBUG_PROPAGATE_EXCEPTIONS = True to my settings.py And I got the following error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'favicon.png' Only place where there was even a mention of 'favicon.png' was as an html comment in my login html template file, login.html contained the following in head: <title>Login</title> <!-- <link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/> --> when I deleted the favicon.png html comment so that code became: <title>Login</title> I no longer got a 500 server error, and things worked again. How can an html comment cause an error in my code? I thought it was impossible for an html comment to cause an error.