Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Server Error (500) on django herokuapp while sending email from gmail SMTP
I have created a Django app and deployed on to Heroku. I have a view which sends invitation to a new person. Everything is working fine on the local machine. After I deployed it on to Heroku with DEBUG=FASLE in setttings.py I'm getting an error Server Error (500) here is what i have added in my settings.py file EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'youremail@gmail.com' EMAIL_HOST_PASSWORD = 'yourpwd' # lesssecureappas - https://myaccount.google.com/u/2/lesssecureapps?utm_source=google-account&utm_medium=web # cpatcha -- https://accounts.google.com/b/0/DisplayUnlockCaptcha EMAIL_SUBJECT_PREFIX = 'test' SERVER_EMAIL = EMAIL_HOST_USER I have even allowed access to captcha and less secure apps. It is working fine for 24 hours on production when I grant access. The very next day it is rasing the same error. How to approach this issue. I have hardcoded the values instead of variables. Please suggest any ideas? -
failed getting value from django .env
I'm using Django environ and when I try to get a value from .env it raise the following exception django.core.exceptions.ImproperlyConfigured: Set the FRONTEND_URL environment variable I load with the command: env = environ.Env() environ.Env.read_env() frontend_url = env('FRONTEND_URL') in the .env file I have: FRONTEND_URL=http://127.0.0.1:8000 I tried to add " to the value and the .env file is in the same folder manage.py. What is the problem here and how can I solve it? -
django rest framework : Is possible to create a put/patch request without using primary key?
I want to update 2 fields is_exempted and comments from the data I get using put http method. And I can get multiple recommendation data from http method. And model doesn't have a field which I can consider pk for each account_id there can be multiple entries. models.py class Recommendation(models.Model): account = models.ForeignKey(Accounts, on_delete=models.CASCADE) account_name = models.CharField(max_length=255, blank=True, null=True) instance_id = models.CharField(max_length=255, blank=True, null=True) month_year = models.CharField(max_length=50, blank=True, null=True) instance_type = models.CharField(max_length=255, blank=True, null=True) is_exempted = models.CharField(max_length=50, default='no', null=False) comments = models.CharField(max_length=255, blank=True, null=True) serializers.py class RecommendationSerializers(serializers.ModelSerializer): class Meta: model = Recommendation fields = ( 'account_id', 'account_name', 'instance_id', 'instance_type', 'is_exempted', 'comments', 'month_year') views.py @api_view(['PUT']) def update_recommendation_data(request): output = [] if request.method == 'PUT': if request.data: for d in request.data: print(d) serializer = RecommendationSerializers(data=d, partial=False) if serializer.is_valid(): serializer.save() output.append(serializer.data) return Response(data=output, status=status.HTTP_201_CREATED) return Response(data="BAD REQUEST", status=status.HTTP_400_BAD_REQUEST) -
Python strptime not parsing data from imported CSV
I am attempting to import a CSV with lines that include a "created_at" date. I am getting circular errors. The date string I am currently attempting to import is '2020-05-14 16:10:21.360520+00:00' which is on line[2] in my csv file. Here is the code that I am attempting to use: for line in import_csv: if line: import_data = BlogLink() created_at = line[2].split('.') import_data.created_at = datetime.datetime.strptime(created_at[0], "YYYY-MM-DD HH:MM:SS") this gives me the error: time data '2020-05-14 16:10:21' does not match format 'YYYY-MM-DD HH:MM:SS' My alternate for this code is this: for line in import_csv: if line: import_data = BlogLink() created_at = line[2].split('.') import_data.created_at = datetime.datetime.strptime(created_at[0], "%Y-%m-%d %H:%M:%S") This gives me the error: time data '' does not match format '%Y-%m-%d %H:%M:%S' (ie it does not even attempt to include the time data). What am I doing wrong here? -
django-leaflet + leaflet-rastercoord (macOS 10.13.6 + homebrew)
I am working on a postgres based django project to create floor plans. I have experience in python3 but js is new to me. I need this to be running in very basic functionality in the next 6 days. So yes: My sweat turned acid. The goal is pretty damn simple: Floor plan with updating overlays (e.g. blue rectangle marks free storage etc). What I need: Floor plan as base-map rectangular (updating) overlays markers Django-leaflet works fine, but rastercoord is killing me. I simply tried to implement the demo code into my template html and it seems like it just silently fails to execute. Django-leaflet itself works like a charm, markers are displayed and so on. I modified the original example code to use my tiled milkyway image from wikipedia, which works just fine. /* * @copyright 2015 commenthol * @license MIT */ /* global L */ ;(function (window) { function init (mapid) { var minZoom = 0 var maxZoom = 5 var img = [ 6000, // original width of image `karta.jpg` 3000 // original height of image ] // create the map var map = L.map(mapid, { minZoom: minZoom, maxZoom: maxZoom }) // assign map and image dimensions … -
Django: Refused to execute script from some link on iis production but running fine on django test server
Hi I am getting below error while running django app on iis production server but it is running perfectly on django test server 172.16.2.98/:1 Refused to execute script from 'https://172.16.2.98:8005/os.path.join(BASE_DIR,%20%22static%22)/js/jquery-file-upload/vendor/jquery.ui.widget.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled. Please let me know, what is the actual problem -
How do i write a placeholder in Django ModelForms?
Is it possible to convert the help text in Django Models to placeholders in ModelForms? models.py class DietaryHabits(Patient): DIET_CHOICES = (('V', 'Veg'), ('N', 'NonVeg'),) diet_type = models.CharField(max_length=1, choices=DIET_CHOICES, default=False) breakfast = models.TextField(help_text='Describe your daily Breakfast') lunch = models.TextField(help_text='Describe your daily Lunch') dinner = models.TextField(help_text='Describe your daily Dinner') others = models.TextField(blank=True, help_text='Describe your other eating habits') fasting = models.CharField(max_length=5, blank=True) forms.py- class DietaryHabitsForm(forms.ModelForm): class Meta: model = DietaryHabits fields = ['diet_type', 'breakfast', 'lunch', 'dinner', 'others'] widgets = { 'diet_type': forms.RadioSelect, } -
Django login with Allauth and an extended customer user model doesn’t seem to allow for email and password login
Hey guys so basically I’m implementing a custom user model extending from AbstractUser. I am also using Allauth. In previous practice projects I have built I am able to configure Allauth so that I can register new users and login in with only an email and password. This however is implemented without actually extending my user model(I just created the class and the passed). When I do then add custom fields for my users with my current project, and after reading the docs for Allauth about custom user models, I loose that functionality. I have to login with a username. What I would like is to have my login how it works when you don’t extend the user model. Meaning that you can register and login in with you email and password. I have tried all the combinations I can think of using the settings in Allauth docs. I just cant seem to figure it out. Has anyone had a similar experience or just know perhaps what im doing wrong? -
pip install django on windows does not download
i am new to python programming and learning with django. I know the basics and used matplotlib, numby and biopython for biology but 4 days ago, i was trying to download django using pip install django, pip3 install django but the respond i get is shown in the image below. at first i assumed it was a network problem but it was not. i have the latest version of python and updated pip, Since it would not give me any error codes, i cannot fully understand and i have search multiple time to look for an answer but nothing specific to my issue. I aslo tried running it on a virtual environment but it would not work. error message -
Import a python file to another file in Ubuntu (in a Django project)
I am in a file called updateApi.py located in: myprojectdir/dataUpdater/updateApi.py I want to import my django models from: myprojectdir/gaapp/models.py When running the below code within updateApi.py: import sys sys.path.insert(0, '/home/llewellyn/myprojectdir/gaapp/') from gaapp import models I get the error: Traceback (most recent call last): File "./updateApi.py", line 27, in <module> from gaapp import models ModuleNotFoundError: No module named 'gaapp' When changing the above code to this: import sys sys.path.insert(0, '/home/llewellyn/myprojectdir/gaapp/') import models I get the error: Traceback (most recent call last): File "./updateApi.py", line 27, in <module> import models File "/home/llewellyn/myprojectdir/gaapp/models.py", line 7, in <module> class UserD(models.Model): File "/home/llewellyn/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/home/llewellyn/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/home/llewellyn/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/home/llewellyn/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/llewellyn/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/conf/__init__.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I am not sure if it is a django problem or a ubuntu/python syntax problem. The directory tree looks like this: myprojectdir | |_ dataUpdater | |_ updateApi.py | |_gaapp |_models.py It is worth noting that my django app is within the … -
Linking two models in django automatically
I have a problem with trying to link two models together in a Django project. I have two models, Songs and Albums where the Song must be linked to an album using a Foreign-Key-Field. Adding an album works perfectly and each album has a different primary key, the way a user of my website adds a song is by going onto the album page (called detail.html) where there is a button saying 'add song' that takes the user to a forum to add the song. Currently if I add in a Foreign Key Field into the song model it allows the user to choose any album to add the song into which I do not want, I would like the song to be automatically linked to the album with the primary key of the album on the detail. Please help if you can and if anything does not make sense or you need some of the code pease reply and let me know. Thank You. -
How to connect to Linode Server and run on local machine. Django Application
I am hired as a Python/Django Developer. My company has deployed its Django application into LINODE Server. I have experience using the Heroku server, but Pretty much new to this Linode server, have no clue about this. I want to run/Connect to project to that server to run locally on my machine. I have access my GIT repo of project and cloned to my machine(windows), What are the requirements needed to run locally? What is the appropriate question to ask my Manager to get it done? Please share any links/process to it. Thanks in Advance. -
How to store many Linear Regression models in django?
I am trying to build a Django app where a user can upload a CSV file and a sklearn linear model will be created and trained to that dataset. So, each time a new CSV file is uploaded a new model will be created. My question is what options do i have for storing these generated models in Django so that users could later choose which model they wanted to use? I have seen some suggestions for pickling them using cpickle and also using Django's cache framework, how would these options affect performance? -
Django cookies and database storage at same time using forms. One of them does not work when the other does
I'm new to django and webdev as a whole, iam trying to submit data into a form and at the same time store it in a cookie and redirect to the next page using action attribute. index.html does not redirect on submit unless and until it uses action='datetime' in form tag and when it does not redirect it Stores the value in sqlite3 DB but when it does redirect it stores the name in cookie but not in the DB. at one point i got an error when the url set in path for datetime.html was path('datetime/', views.dateTime) error:You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/datetime/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. but that was resolved when i set it to path('datetime', views.dateTime) index.html <!DOCTYPE html> {% extends './base.html' %} {% block body_block %} <h1>LoginForm</h1> <form method='post' > {{ form.as_p }} {% csrf_token %} <button type='submit'> Submit</button> {% comment %} <input type="submit" value="submit" /> {% endcomment %} <!--tried using href="datetime/" in button as well both did … -
Django Rest Framework bulk patch
I'm trying to create an enpoint for bulk patch using DRF. Here is what I have so far: # model.py class A(models.Model): field_1 field_2 field_3 field_4 # serializers.py class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = '__all__' lookup_field = 'field_1' # views.py class AViewSet(viewsets.ModelViewSet): serializer_class = ASerializer lookup_field = 'field_1' def get_queryset(self) return A.objects.filter( field_1=self.kwargs['field_1'], field_2__in=self.request.query_params.getlist('field_2', []) ) # i know im overriding parent update but i don't really care about this functionality def update(self, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), data=request.data, many=True, partial=True) if serializer.is_valid(): self.perform_update(serializer) return Response(serializer.data, status=status.HTTP_200_OK) # urls.py ... a_bulk_update = AViewSet.as_view({ 'patch': 'update' }) urlpatterns = [ ... path('ases/<int:field_1>', a_bulk_update, name='a-bulk-update') ] # and example of functionality in tests.py @pytest.mark.django_db def test_bulk_put_article_link(): client = Client() response = client.post( '/ases/', {'field_1': 123, 'field_2': 134, 'field_3': 'soifdjsdf', 'field_4': 'some_some'} ) response = client.patch( '/ases/123?field_2=134', json.dumps({'field_3': 'other_content'}), content_type='application/json' ) I'm not sure what's going on but for some reason Django operates only on request.data and I'm getting error as such: AttributeError: Got AttributeError when attempting to get a value for field `field_4` on serializer `ASerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' … -
Keep Django selected option (form/select) after refresh
Select option in my Django app is not saved after refresh. Below is my code: <! –– jobs.html ––> {% block content %} <form id="job-main-form" method="get" action="#" class="job-main-form"> <select form="job-main-form" name="specialization" class="form-control" id="specialization"> <option selected="selected" value="all">Všechny obory</option> {% for specialization in specializations %} <option value="{{ specialization|lower }}">{{ specialization }}</option> {% endfor %} </select> <button type="submit" class="btn btn-outline-white-primary job-main-form__button"> <i class="fa fa-search"></i> </button> </form> {% endblock %} # views.py from django.views import generic from .models import Job class JobListView(generic.ListView): model = Job template_name = 'jobsportal/jobs.html' context_object_name = 'jobs' paginate_by = 5 specializations_list = [ 'Alergologie', 'Anesteziologie', ] def get_queryset(self): q = self.model.objects.all() if self.request.GET.get('specialization') and self.request.GET.get('specialization') != "all": q = q.filter(specialization__icontains=self.request.GET['specialization']) return q # models.py from django.db import models # Create your models here. class Hospital(models.Model): PRAHA = 'PHA' STREDOCESKY = 'STC' REGIONS = [ (PRAHA, 'Hlavní město Praha'), (STREDOCESKY, 'Středočeský kraj'), ] key = models.CharField(max_length=20) name = models.CharField(max_length=200) region = models.CharField(max_length=50, choices=REGIONS) city = models.CharField(max_length=50) website = models.CharField(max_length=300, default="") logo = models.CharField(max_length=300) objects = models.Manager() def __str__(self): return self.name class Job(models.Model): title = models.CharField(max_length=300) specialization = models.TextField() detail = models.CharField(max_length=300, default="") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE) objects = models.Manager() def __str__(self): return self.title # urls.py from django.urls import path from . … -
SearchVectorField "cannot insert into column" error
I've added GIN index to my db ALTER TABLE mtn_order ADD COLUMN textsearchable_index_col tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(descr, '') || ' ' || coalesce(descrrep, ''))) STORED; CREATE INDEX textsearch_idx ON mtn_order USING GIN (textsearchable_index_col); and textsearchable_index_col = SearchVectorField(null=True) to my model and now when i'm trying to save new instance i get: ProgrammingError at /order/create/ cannot insert into column "textsearchable_index_col" DETAIL: Column "textsearchable_index_col" is a generated column. -
How Do i Configure Django Filter?
I need to implement a functionality of filtering teachers by their first names.So i installed the Django-filter package.Unfortunately it is not filtering though the URL is changing. Also fields with choices,boolean or foreign keys to parent models are not rendering. The model: class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True,blank=True) fname = models.CharField(max_length=200) lname = models.CharField(max_length=200) tsc_no = models.CharField(max_length=200,blank=True,unique=True) email = models.CharField(max_length=200,blank=True,unique=True) password = models.CharField(max_length=200,blank=True) profile_picture = models.ImageField(verbose_name='profile_picture',upload_to='photos/%Y/%m/%d',blank=True) national_id = models.CharField(max_length=200,unique=True) dob = models.DateField(blank=True) phone_number = PhoneNumberField() status = models.CharField(max_length=200) clas_teacher = models.CharField(max_length=200,blank=True) date_of_join = models.DateField(blank=True) timetable_color = models.CharField(max_length=200) def __str__(self): return self.fname The filters.py: import django_filters from .models import Teacher from django_filters import DateFilter,CharFilter class TeacherFilter(django_filters.FilterSet): class Meta: model = Teacher fields = ['fname'] The view: def dallteachers(request): teachers = Teacher.objects.all() myFilter = TeacherFilter(request.GET,queryset=teachers) return render(request = request, template_name='main/dallteachers.html', context= { "teachers": Teacher.objects.all, "myFilter": myFilter, }, ) The template: <form action="" method="get"> {{myFilter.form}} <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit" style="height: 89%;"><i class="fas fa-search"></i></button> </div> </form> -
how to group different models in separate template in django rather than admin base file
I am working on a project where i don't want to write my models at the admin base file I want to group models in a template which shall be opening from the admin base view and shall then open all my models and further when i click on the model it shall open each model's list page. -
Django Pagination with Django-Filter
Hello Django community. I am at a complete loss as to why pagination is not working for me, as I am not getting any errors, and only certain aspects of it aren't working. I am using a function based view, and am also filtering my queryset with Django-Filter. I know that the page_obj is being passed through the context, and is a django pagination object, because the conditions which require it in the template are passing. (the links for page1, page2, next page, last page, etc.. populate). What isn't happening, is that it is not actually paginating. The buttons appear, and a pagination object is passed, however the full queryset still appears on page 1, and if I click on page 2, 3, or whatever, it is the same exact queryset. I have tried playing around with what I pass as the object_list to the paginator, as well as removing the django-filter object, and playing around with the object_list again. Really confused as this seems like I'm doing something obviously wrong but I've been stuck on it long enough to resort to asking for help. Thanks in advance. views.py def home(request): reports = Report.objects.all().order_by('-date') # Instantiating the filter myFilter = … -
static django css files are not loading up
I downloaded a free Template and I am setting it up so that I can design its backend. The template i download can be found here: [Pillow Selling website free template from colorlib.][1] After going through many Q&A's from different problem who had the same problem as me. I set up the things as follows: My settings file look like this: other settings... TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') I included this in my app urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my index.html has all the .css, .png, .jpg files linked like this <link rel="icon" href="{% static 'staticfiles/img/favicon.png' %}"> I have done this before too with some other website but I don't know why is this not working this time. -
Execute a Go script from Django webapp safely
How do you launch a Go script in a django app safely? I made a go script which is self contained. I would like to be able to launch a job from a django web app (I use celery to have the job run in the background). What would be the proper/safer way of achieving this? Maybe a way to isolate this process? I feel that running... os.system(f"./goscript -o {option1} -b {optiom2}") ...is quite unsafe. as a bonus, I'd like to be able to get the output to see if the script crashes etc... but that is a bonus question. -
Nginx cannot serve backend's static files
Nginx is set up with both frontend and backend services in Docker - both are working without any issues apart from backend static files which are not being served by nginx (http://api.example.com/static/...). Since frontend is SPA and consists of static files already - they have no issues being served from within nginx container. However, nginx is not serving backend static files. The static files are definitely in the nginx container (/home/app/web/static/) - however nginx is giving the following error when checked in the console - this is probably because the CSS file below would return 404 (which is html page) - hence it cannot apply html to CSS . Nginx log files are clear. Refused to apply style from http://api.example.com/static/admin/css/responsive.css because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. P.S. Backend framework is Django whereas Frontend is Vue. nginx.conf file upstream api { server backend:8000; } server { listen 80; server_name example.com; root /usr/share/nginx/html; index index.html index.htm; # frontend location / { try_files $uri $uri/ /index.html; } location @rewrites { rewrite ^(.+)$ /index.html last; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } server { … -
How to implement search in paginated chat django rest framework
I am creating a chat application using django rest framework and angular. There are two models for that. 1. chat_room 2. messages now I am showing chat messages base on chat_room using paginations. how can I implement the search message feature in the chat? -
How to use default value in Django model once set to null?
I have this model in my django app: class Person(models.Model): name = models.CharField(max_length=50) image = models.ImageField(blank=True, upload_to='images', default='default/static/image/here') def __str__(self): return self.name When making a Person object, if left empty, the "image" is set to a default value, but later, if the user decides to remove his image, his image will no longer be set to default but to NULL instead. How can I make it so that whenever image is NULL again, it automatically brings back the default value?