Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
production server git repo ahead of origin/main
I am going on production with my Django app and don't know if I'm on top of best practices. I pull from my GitHub repo main branch into my production server's git main. I set up my git email and password on the production git environment (I doubt if this is right if it is not how can I undo it). I do make some small changes on the production repository which makes it ahead of the origin/main. I really don't want to push before I can pull again. How can I make changes to my production git environment and still be able to pull from the origin/main without being prompted to push first or being told I'm ahead of origin/main -
In Django Rest Framework, how do I filter/Search in URL a serializer when it's nested in another serializer?
I'm creating an API which has nested data like in the picture enter image description here Now how to search nested data in URL here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) Here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'param'] and here's my view for the api class RobotViewSet(mixins.ListModelMixin,GenericViewSet): queryset = Robot.objects.all() serializer_class = RobotSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['robot'] authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] in the api url if i want to search particular robot then using this url url/?robot=robotname i'm able to search that particular robot . But how can i search particular nested data using URL? -
Django email authentication using djoser package
I'm using django-rest-framework in the project- Each time I try to login in then I get "non_field_errors": [ "Unable to log in with provided credentials." ] }``` I need to have only email and password -
Django annotate Multiple Sum with one Many to Many field and group By
Regarding my previously asked question with the same title, let's now, take this models: class Server(models.Model): name = models.CharField(max_length=100, null=False, blank=False) cpu = models.PositiveIntegerField(null=False, blank=False) ram = models.PositiveBigIntegerField(null=False, blank=False) customer = models.ForeignKey( Customer, related_name='Servers', on_delete=models.SET_NULL, null=True, blank=True ) city = models.ForeignKey( City, related_name='Servers', on_delete=models.CASCADE, null=True, blank=True ) class Disk(models.Model): server = models.ForeignKey( Server, related_name='Disks', on_delete=models.CASCADE, null=False, blank=False ) size = models.PositiveBigIntegerField(null=False, blank=False) class Customer(models.Model): name = models.CharField(max_length=255, blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField( blank=False, null=False, default=False) class City(models.Model): name = models.CharField(max_length=255, blank=False, null=False) country = models.ForeignKey( Country, related_name='Cities', on_delete=models.CASCADE, null=False, blank=False ) class Country(models.Model): name = models.CharField(max_length=255, blank=False, null=False) I would like to know how many Server with the sum of every CPU, RAM, Disk space I have per customer per country. Every Server has a city, every city is in a country. Some Server has no customer yet, but I still need to know how many server, CPU, ... I have with no customer (can eventually create an "Unknown" Customer to not set it to None in Server). Any Help will be appreciate ! Thank you !! -
CSS not rendering properly with angular internationalization messages.xlf file
I am having an issue that when i am running. ng serve --aot --port 4200 --host 0.0.0.0 to serve my angular project all the static files (css,images) are rendering perfectly. But when i am running with internationalization command in angular css and images are not rendering. ng serve --aot --i18nFile=src/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr --base-href /fr/ --port 4200 --host 0.0.0.0 The app front end is in angular and backend on django. Any help would be appreciated. error -
gaierror on django when trying to register a user and send a token via email
I am getting the error below on windows 10 when I try registering an account and send a registration link via email. My internet connection is stable. i have successfully run the telnet command (telnet smptp.gmail.com 587) Exception Type: gaierror Exception Value: [Errno 11001] getaddrinfo failed Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\socket.py, line 748, in getaddrinfo -
inherit mqtt Initializer class without Initializing client.connect and loop_start method -django
i have a mqtt initializer class class Initializer(): def __init__(self): self.client = mqtt.Client(mqtt_server+str(int(time.time()))) self.client.username_pw_set( username=mqtt_username, password=mqtt_password) self.client.on_connect = self.on_connect self.client.subscribe( "topic") self.client.connect(broker, mqtt_port) self.client.loop_start() inherited this class to another class class publishdata(Initializer): def __init__(self): super().__init__() self.client.on_message = self.on_message self.client.on_subscribe = self.on_subscribe def on_subscribe(self, client, userdata, mid, granted_qos): print("Subscription started") def on_message(self, client, userdata, message): print("message.topic", message.payload) def begin(self,topic,data): self.client.publish( topic, str(data)) publishData = PublishData() publishData.begin(topic,data) publish and subscribe works properly. but when i call publishedData .client.connect and client.loop_start in the Initializer class also runs.i dont want that to be excecuted on every publish call. is there any better way to do this -
django model - TypeError: expected string or bytes-like object
when I exectued python3 manage.py migrate in /manage.py I got an error said TypeError: expected string or bytes-like object Here is my model.py What is the probelm here? from django.db import models # Create your models here. class Event(models.Model): eventname = models.CharField(max_length=60, ) description = models.TextField(max_length=200, ) eventdate = models.DateField(auto_now=True) Adagree = ( ('email', 'email'), ('phone','phone'), ('post','post'), ) adagree = models.CharField(max_length=10, choices=Adagree) -
How can I translate forms in Django?
I add a field to user model for language choice: language = models.CharField(max_length=250, default='English') For now, I have two language; Turkish and English. How can I translate my forms when user select Turkish as language. This is my example form: class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ['title', 'document_type', 'year', 'payment_behavior'] labels = { "payment_behavior": "Please Select the Payment Behavior of the Customer: ", "document_type": "Document Type", "title": "Document Name", "year": "Financial Table Year" } And this is my related model: class Pdf(models.Model): ... payment_behavior = models.CharField(max_length=200, default='Select', choices=PAYMENT) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) title = models.CharField(max_length=200) year = PartialDateField(null=True, blank=False) ... -
Recommended way of serializing Django RawQuery
i have complex query to serialize,but this example can represenr my table. i want to make this raw query to json,i have tried using serializers.serialize but its only return field from one object. referencing this : How to pass RawQuerySet result as a JSONResponse in DJango? details = 'SELECT DISTINCT IR.id,idn_description,idn_likelihood,idn_dampak,idn_risk_value,identifikasi_risk_id,mtg_description,mtg_likelihood,mtg_dampak,mtg_risk_value FROM public.library_identifikasirisiko IR join library_riskassessment RA ON IR.idn_risk_assessment_id = RA.id JOIN library_mitigasirisiko MR ON MR.identifikasi_risiko_id = IR.id where RA.status_id = 1' jsonTest = serializers.serialize('json', IdentifikasiRisiko.objects.raw(details), fields=('IR.id','idn_deskripsi','idn_likelihood','idn_dampak','idn_nilai_risiko','mtg_deskripsi','mtg_likelihood','mtg_dampak','mtg_nilai_risiko' )) im expecting the value of JsonTest like this { id: idn_description: idn_likelihood: .. .. mtg_description: mtg_likelihood .. .. } -
Filter GenericForeignKey by list of different model objects
I am trying to build an activity logs by a User or any other model object. These are the models related with logging the activities: class Activity(models.Model): """ An activity log : Actor acts on target Actor can be a User or a model Object """ actor_content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name="actor_type") actor_object_id = models.PositiveIntegerField() actor = GenericForeignKey('actor_content_type', 'actor_object_id') description = models.TextField() target_content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, related_name="target_type") target_object_id = models.PositiveIntegerField() target = GenericForeignKey('target_content_type', 'target_object_id') class Follow(models.Model): """ A user can follow any User or model objects. """ user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() follow_object = GenericForeignKey('content_type', 'object_id') Suppose: Thor follows user Loki // User follows User Thor follows user Stark // User follows User Thor follows project Avenger // User follows Project And suppose these are activities: Nick Fury Created a project "Shield" Nick Fury Created a project "Avengers" Stark created a project "Mark II" Avengers added Vision Dr Strange created a project Dormammu I can get the user Thor: thor = User.objects.get(email="thor@gmail.com") And get the list of users/objects followed by Thor: thor.follow_set.all() <QuerySet [<Follow: thor@gmail.com follows loki@gmail.com>, <Follow: thor@gmail.com follows Stark@gmail.com>, <Follow: thor@gmail.com follows Avengers>]> Now to get the list of activities followed … -
403 errors with AWS S3 when loading static files
I am building a Django app and try to use S3 bucket to store static files like JavaScript and CSS. I successfully uploaded the static files, and I can see that through S3 console. But I get 403 errors when my site tries to load static files from my S3 bucket. So I checked my permissions and made sure the S3 bucket is accessible to anyone. [![enter image description here][1]][1] But I still get 403 errors in inspector. i don't think my settings.py is related to this, but I show you my settings.py in case it's relevant to the problem. # AWS S3 Static Files Configuration AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATICFILES_DIRS = [ 'atgs_project/static', ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'us-west-2' AWS_S3_USE_SSL = False AWS_S3_ENDPOINT_URL = "https://my-ecommerce-app-bucket.s3.amazonaws.com/" THank you in advance. -
How to append a paperclip icon in email body - Gmail
I have integrated Gmail in Python and it's working great. Now I need to append a paperclip icon in the list view of email just like the Jira appends to its emails. (But no physical image is actually attached) . I'm unable to do so in my scenario because there's no physical attachment in my email. So I'm wondering how Jira is doing it. Does anyone get the same scenario? A screenshot is also attached for further clarification. Happy Learning. -
How to deploy django app on given domain name?
I have been given domain name 'example.com'. I can access all files using FileZilla. I am creating website using django. Currently there is only one page in website named as 'index.html'. I have .htaccess file. my website is running on my local machine. I want to deploy this app on given domain name. How can i deploy django website on given domain name. .htaccess file : - AuthName "Username and password required" AuthUserFile /var/www/somename/example.com123/.htpasswd AuthType Basic Require valid-user order deny,allow deny from all allow from ip1 allow from ip2 allow from ip3 allow from ip4 Satisfy Any #####Apache################## Options +SymLinksIfOwnerMatch #####Rewrite#################### RewriteEngine on #####Rewrite################# <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> #####index.html RewriteCond %{THE_REQUEST} ^.*/index.(html|htm|shtml|shtm|php) RewriteCond %{REQUEST_URI} !(^/phpMyAdmin/) RewriteRule ^(.*)index.(html|htm|shtml|shtm|php)$ example1.com <Files ~ ".(js|gif|ico)$"> Header set Cache-Control "max-age=2592000, public" </Files> <Files ~ ".(jpe?g|png)$"> Header set Cache-Control "max-age=86400, public" </Files> wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() -
TypeError at /login/home/ || argument 1 must be a string or unicode object
My app is trying to connect to an existing Microsoft SQL server and print a set of variables from the database (Sage 200) When the app moves to the home page (Where the data is supposed to be printed) it gives the above-mentioned error message. Here is the error in more detail: TypeError at /login/home/ argument 1 must be a string or unicode object Request Method: GET Request URL: http://localhost:8000/login/home/ Django Version: 3.2 Exception Type: TypeError Exception Value: argument 1 must be a string or unicode object Exception Location: C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\views.py, line 17, in home Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\KylePOG\\Documents\\GMA Programming\\accConnect', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 23 Aug 2021 06:24:37 +0000 Traceback Switch to copy-and-paste view C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\views.py, line 17, in home 'UID=[UID] ;' 'PWD=[PWD];') def home(request): query = "SELECT top 10 * FROM [[DBNAME]].[dbo].[_etblGLAccountTypes]" conx = pyodbc.connect(cnxn) … cursor = conx.cursor(); cursor.execute(query); data = cursor.fetchall() return render(request , 'main/home.html' , {"data":data}) ▶ Local vars The code that it is trying to execute in the views tab … -
Manytomany field custom display objects in Django
I'm developing a site where I can manually add photographers to the Django adminpanel and then upload the images taken by them. I used the default User system in Django and added a field here that shows this user is a photographer or not : from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_photographer = models.BooleanField(default=True) Also, in the model that I need to put the images, I used ManyToMany field for photographers (because these photos may have been taken by several people) : from registration import User class Photo(models.Model): ... photographers = models.ManyToManyField(User) The problem is that when adding a new image to the admin panel, users who are not photographers and the is_photographer is False, is also displayed in the Photographers. I want only users who are photographers to be displayed and not normal users. -
Extract specific data from a bunch of data in python
How can I extract the companies name from the given below data without using NLP in python, Although it works perfectly with NLP but my task is to complete it without NLP........... ['working as associate ui developer in tarang software technologies bangalore from august 2014 excellent decision making skills with a positive approach work experience working as associate ui developer in tarang software technologies bangalore from august 2014 working as associate ui developer in tarang software technologies bangalore from august 2014 to till date worked as software engineer in centre for educational and social studies cess bangalore from'] None july 2012 to august 2014 technical skills to till date worked as software engineer in centre for educational and social studies cess bangalore from july 2012 to august 2014'] -
Get disctinct values from in a queryset django?
I have modelwith 2 foreignkeys. class NewModel(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) user_g_id = models.ForeignKey(User, on_delete=models.CASCADE) This is my queryset. It counts the number of male users but i want distinct number of male users from both the fields. male_count = newmodelqueryset.filter( Q(user_id__gender_id=male['id']) | Q(user_g_id__gender_id=male['id'])).count() -
SearchFieldError - Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields
I have a elasticsearch backend (7.14.0) and wagtail (2.14.1) and I want to include a fulltext-search at the body field of my page. When search something in frontend, I get SearchFieldError at /search/ Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields. Request Method: GET Request URL: https://my.site/search/?query=impres Django Version: 3.2.4 Exception Type: SearchFieldError Exception Value: Cannot search with field "body". Please add index.SearchField('body') to Page.search_fields. Exception Location: /var/www/vhosts/my.site/dev4/venv/lib/python3.6/site-packages/wagtail/search/backends/base.py, line 163, in check Python Executable: /var/www/vhosts/my.site/dev4/venv/bin/python Python Version: 3.6.9 Python Path: ['/var/www/vhosts/my.site/dev4/venv/bin', '/var/www/vhosts/my.site/dev4/mysite/mysite', '/var/www/vhosts/my.site/dev4/mysite', '/var/www/vhosts/my.site/dev4', '/usr/share/passenger/helper-scripts', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/var/www/vhosts/my.site/dev4/venv/lib/python3.6/site-packages'] Server time: Mon, 23 Aug 2021 05:24:18 +0000 my views.py: from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.template.response import TemplateResponse from wagtail.core.models import Page from wagtail.search.models import Query def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: #search_results = Page.objects.live().search(search_query) # exclude some search results search_results = Page.objects.live()\ .exclude(title='Sie sind nun ausgeloggt.')\ .exclude(title='Sie sind nun eingeloggt.')\ .exclude(title='Passwort erfolgreich geändert.')\ .search(search_query, fields=["title", "body"]) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return TemplateResponse(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) my models.py: … -
Serial request to TokeView of django rest framework social oauth2 causes error
I have mobile backend created with django and I use django rest framework social oauth2 TokenView to refresh access token. from rest_framework_social_oauth2 import views as auth_views urlpatterns = [ path('my-token-path', auth_views.TokenView.as_view(), name = 'my-token-path'), ] The mobile app automatically try to re login when any api request receives Http 401. My mobile app makes several api request at launch. When the app launches and toke was expired, several api requests receives 401 thus each one accesses TokenView to re login using refresh token. When this happens, some requests to TokenView fails with error log saying datbase is locked. How can I prevent this error? -
Django List Based Off Previous List
I am trying to make a dynamic list of choices. That is, the choices change based on a previous answer. For example, if country = ["USA", "Canada", "Mexico"], then click "USA" will generate a list with the 50 US States, state = ["Alabama", "Alaska"]. I tried to do an if statement, however, that did not seem to work. I am not sure what the best option for this is. class Property(models.Model): address = CharField(max_length = 200) city = CharField(max_length = 200) COUNTRY_LIST = [ ("USA", "United States"), ("CAN", "Canada") ] country = CharField(max_length = 3, choices = COUNTRY_LIST) USA_STATE_LIST = [ ("AL", "Alabama"), ("AK", "Alaska"), ("AZ", "Arizona") ] CAN_STATE_LIST = [ ("AL", "Alberta"), ("BC", "British Columbia") ] state = CharField(max_length = 2, choices = ?) -
How do i add another field to Django's default user model. For instance, adding a field called matricule
I am working on a project where by users needs to use their matricules and password as a form of authentication. Please how do i go about adding a matricule to Django's default user model -
How to generate form elements from the forms.Form classe in Django?
In my project, a feature has multiple possible scopes. class ProjectForm(forms.Form): features = Feature.objects.all() i = 0 for feature in features.iterator(): scopes = RectificationAssetMultiField( required=False, queryset=Scope.objects.filter(feature=feature.pk), widget=forms.CheckboxSelectMultiple, ) i+=1 class Meta: model = Project I need to create groups of "RectificationAssetMultiField". With my current code, only the last set of scopes are desplayed with {{ form.scopes }}. I only could think of variable name generation (scopes0, scopes1... for each feature) but I'm not sure if it's the right way and if it can work or not. How could I achieve that? -
How to edit a form field to add some condition using Django template
I have a form (ModelForm, Model and view). Everything works fine but there is a new requirement in the project and one of the text-input is no longer simple, I need to use some Django template (if condition). This is exactly the HTML representation of the input that I need (and it works separately): <input class="form-control ts_project" id="ts_project" name="ts_project" type="text" {% if entry.project %}value="{{ entry.project.id }}: {{ entry.project.name }}"{% endif %}> What I have tried: edit the attributes of the widget in the forms.py so that it looks as close as possible to the HTML code above but it has been impossible for me. forms.py: from django.forms import ModelForm from django import forms from expense.models import Expense class ExpenseForm(ModelForm): class Meta: model = Expense fields = ['project'] widgets = { 'project': forms.TextInput( attrs={ 'class': 'form-control ts_project', 'id': 'ts_project', 'name': 'ts_project', {% if entry.project %} 'value':'{{ entry.project.id }}: {{ entry.project.name }}' {% endif %}, } ) } The code doesn't work but I can't think of another way to make it work. class, id and name working as expected if I delete value and all the Django template code. models.py (truncated): from django.db import models from django.contrib.auth.models import User from project.models … -
socket.gaierror: [Errno 11001] getaddrinfo failed django - paho mqtt
initialized paho mqtt in django urls.py . when i run django i am getting this error socket.gaierror: [Errno 11001] getaddrinfo failed.