Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to loaddata only if it's not exist in DB with Django fixtures
I have some initial data to load with ./manage.py loaddata command. It's working correctly the problem is that when I call the loaddata function I want to load that data when the data is not there already if the data already loaded then I want to skip this step -
User login in Django + React
I have looked through quite a few tutorials (e.g. this, this, and this) on user authentication in a full-stack Django + React web app. All of them simply send username and password received from the user to the backend using a POST request. It seems to me that, if the user leaves the computer unattended for a minute, anyone can grab his password from the request headers in network tools in the browser. Is this a valid concern that must be taken care of? If so, how should these examples be modified? A tutorial / example of the correct approach would be appreciated. -
Django reset password via SMS
I'm working on a Django app, and I would like to authenticate users using their phone numbers, I also would like users to be able to reset their passwords via SMS, is there a way to do it, I can't seem to find anything referencing password reset via SMS in Django, thanks in advance. -
How to use open AI Codex in existing python projects.?
I want to develop a proof of concept based on open AI codex.I have tried with documentation but i am not getting that ,from where i have to start .So i want to know that how to develop a project or proof of concept with codex.I have knowledge in python So just want to use the Codex to use it in my existing projects. https://beta42.api.openai.com/codex-playground I have tried curl https://api.openai.com/v1/engines/davinci/completions -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_API_KEY" -d '{"prompt": "This is a test", "max_tokens": 5}' -
Related Field got invalid lookup: icontains - While Search Tag
I am building a BlogApp and I am trying to implement a search field which will search ( filter ) with entered tag. When i try to access the page then it is keep showing Related Field got invalid lookup: icontains models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() views.py from taggit.models import Tag def search_page(request): query = request.GET.get('p') object_list = BlogPost.objects.filter(tags__icontains=query) context = {'posts': object_list, 'query': query} return render(request, 'search.html', context) I have also tried different methods but still showing the same error. I tried .filter(tags__in=query) then it showed NoneType' object is not iterable The i tried Tag.objects.filter(question__tags__icontains=query) then it showed Related Field got invalid lookup: icontains Any help would be much Appreciated. Thank You in Advance. -
save and load and fine tune ftlearn model?
I am trying to implement and simple chatbot model in django. So, I need to save the model and the weights in static files, to reuse them. Also, I need to add training data the to pre-trained model ( I think this called fine-tuning). problem1: when I use this code I got an error sayes NotFoundError: Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error: new_model = tflearn.DNN(net) new_model.load('my_model.tflearn') problem2: I need to add new training data each week and in the code I added traning data only once. See the full code -
How could I translate a spatial `JOIN` into Django query language?
Context I have two tables app_area and ap_point that are not related in any way (no Foreign Keys) expect each has a geometry field, respectively of polygon and point type. The bare model looks like: from django.contrib.gis.db import models class Point(models.Model): # ... geom = models.PointField(srid=4326) class Area(models.Model): # ... geom = models.PolygonField(srid=4326) I would like to create a query which filters out points that are not contained in polygon. If I had to write it with a Postgis/SQL statement to perform this task I would issue this kind of query: SELECT P.* FROM app_area AS A JOIN app_point AS P ON ST_Contains(A.geom, P.geom); Which is simple and efficient when spatial indices are defined. My concern is to write this query without hard coded SQL in my Django application. Therefore, I would like to delegate it to the ORM using the classical Django query syntax. Issue Anyway, I could not find a clear example of this kind of query on the internet, solutions I have found: Either rely on predefined relation using ForeignKeyField or prefetch_related (but this relation does not exist in my case); Or use a single hand crafted geometry to represent the polygon (but this is not my … -
How to ensure a DKIM signature is sent when sending an email in Django through a custom office365 domain?
I have a domain registered with GoDaddy, and an associated Office365 account for email. I have setup DKIM and DMARC records for the domain. I have successfully checked that these are configured correctly by testing out emails sent from the office365 client to glockapps.com/inbox-email-tester-report and other sites. However, if I send a mail from the exact same address through my Django application, the DKIM signature is missing. I receive this error on glockapps Error details: This message doesn't contain DKIM signature matching your domain Is it a configuration issue in Django? These are my current settings. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = "hello@---.com" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = "---" EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True -
Tastypie resource filtering through foreign keys
I have some Django (3.1) models connected through foreign keys class Drone(models.Model): serial = models.CharField(max_length=200, null=False, unique=True) class Dive(models.Model): measurement_time = models.DateTimeField(db_index=True) drone = models.ForeignKey( Drone, on_delete=models.PROTECT, null=True, ) class Density(models.Model): measurement_time = models.DateTimeField(db_index=True) depth = models.IntegerField() density = models.FloatField(null=True) dive = models.ForeignKey( Dive, on_delete=models.PROTECT, db_index=True, null=True, ) I have a Tastypie (0.14.3) ModelResource class for my API defined like class DensityResource(ModelResource): class Meta: queryset = Density.objects.filter(dive__drone_id=13).order_by('-measurement_time', 'depth') that works as I'd expect for the single dive__drone_id. I want to implement get parameter filtering so I can do something like /?order_by=-measurement_time&order_by=depth&dive__drone_id=13 so I rewrote this class to class DensityResource(ModelResource): class Meta: queryset = Density.objects.all() filtering = { 'dive__drone_id': ALL } ordering = ['measurement_time', 'depth'] and the ordering works fine but not the filtering. What am I missing here? -
How do I access a single field while using For Loop to iterate through all the fields of a ModelForm in Django Template?
I have a model which has four ForeignKey fields, so they are dropdown fields in the form. class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) The forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "patient_type" : forms.Select(attrs={"onblur":"mf();"}), "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();", "onblur":"tp();"}), "total_package" : forms.NumberInput(attrs={"onfocus":"tp();", "onblur":"onLoad();"}), 'date_of_admission': DateInput(attrs={'type': 'date'}), The views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') if fm_package.is_valid(): package=fm_package.save() IpdReport.objects.create(patient=package.patient, package=package) fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) else: fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) The Template: <form action="" method="post" novalidate> {% csrf_token %} {{form5.non_field_errors}} {% for fm in form5 %} <div> {{fm.label_tag}} {{fm}} <span>{{fm.errors|striptags}}</span><br><br> </div> {% endfor %} <button type="submit" id="savebtn">Save</button> </form> Now, what I want is to insert an Anchor Tag next to all the foreign_key fields, in the template, to add a new object into the original table. For example, an Add Patient option next to the Patient's dropdown field, when clicked, a new, small window would show up with Patient form. The user enters the new patient's data, saves it and the same name shows up in the dropdown. But as I am using a For Loop in the template, how would I be able to access those foreign key fields … -
How do I use the key that is passing from page to page with django formset?
I have this key that I use to pass from page A to page B. How do I use this key with a formset to get the data according to the key. For model, its just the model.objects.get(variable = pk). But how about formsets? Tried the following but it doesnt work di_formset = modelformset_factory(DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), can_delete=True) deviceInterface = di_formset.objects.get( I2DKEY=pk) -
django-cors-headers issue with Python 3.9 and Django 3.2.0
I have spent almost a day without any solution to this problem. I have applied all the solutions suggested by different folks on different forums. Recently we have upgraded the Python version of our project from 3.5 to 3.9. Upgraded Django version from 1.8 to 3.2.0. Post that this CORS issue is coming. It is working fine on my local MacBook. But when we deploy it on the Cent OS server, this issue starts appearing. in my settings.py I have added - MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # must be before CommonMiddleware 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'reversion.middleware.RevisionMiddleware', 'insights.middleware.RaiseErrorMiddleware', 'insights.middleware.IAMAuthenticationMiddleware', ) + getattr(settings_local, 'LOCAL_MIDDLEWARE', ()) ============== CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "X-csrftoken", "X-Requested-With, Content-Type", "X-requested-with", "X-I-Token", "x-employer-key" ] Below is our server configuration. NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" Can anyone please help. me with the solution. -
How to Optimize django application for images and static files
I'm building a website using Django(3) in which we have implemented blogs to post articles on the site. For each blog post, we have to add images one feature image and the other may need to be used within the post. You can find the site at: https://pythonist.org I can see in google console my website is too slow due to images and static css/js files. I'm compressing the image on uploading using the code below: from imagekit.models import ProcessedImageField class Course(models.Model): title = models.CharField(max_length=250, blank=False) slug = models.SlugField(blank=True, max_length=120) description = RichTextUploadingField(config_name='default') featured_image = ProcessedImageField(upload_to='course_images/', format='JPEG', options={'quality': 80}, blank=False) I'm using safe to load template variables and utilize cache, prefetch_selected, and other basic optimization tweaks. But are there other practical ways to load my images and static files faster? My site has been deployed on Heroku. -
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.