Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically assigning User token to custom profile model django rest framework
I currently have a signal that automatically creates a Token object for a User when they sign up to the website. I also have a custom User model, UserProfileInfo, in which I have a field that connects a Token to the User token = models.OneToOneField(Token,related_name='token',on_delete=models.CASCADE,blank=True,null=True) However, I want this to be automatically assigned when the userprofileinfo is created, which happens in a signal. @receiver(post_save, sender=User) def create_auth_token(sender, instance, created, **kwargs): if created: token = Token.objects.create(user=instance) UserProfileInfo @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: UserProfileInfo.objects.create(user=instance) else: instance.userprofileinfo.save() (the first signal creates a token, the second creates the userprofileinfo) I want to know how I can automatically assign a token to a user when the userprofileinfo is created. -
Django ModelAdmin use custom query
Hi currently i'm having trouble add a custom ModelAdmin section to the app admin side without using any defined model in the models.py For example i have 3 models(topups, withdrawals, transfers) and i would like to add a separate ModelAdmin transactions section that a combination from those 3 model, because i like it's paging, change listing and detail view. So if i have a query for example like so: cursor = connection.cursor() cursor.execute(''' SELECT * FROM (SELECT id, user_id, 1 AS transaction_type, method, NULL AS to_bank, NULL AS to_address, user_id AS to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(received) AS confirmed FROM topups WHERE deleted IS NULL UNION ALL SELECT id, user_id, 2 AS transaction_type, method, NULL AS to_bank, to_address, to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM transfers WHERE deleted IS NULL UNION ALL SELECT id, user_id, 3 AS transaction_type, method, to_bank, to_address, NULL AS to_account, to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM withdrawals WHERE deleted IS NULL ) AS T WHERE (user_id =''' + str(user.id) + ''' OR to_account =''' + str(user.id) + ''') ORDER BY created DESC''' ) row = namedtuplefetchall(cursor) … -
need help separating a Django function into 2 distinct parts
I'm continuing to make progress on a personal cycling data website. What I'm currently working on is trying to take a function which, at the moment, is run all at once, and turn it into two separate pieces. I'm pulling data from Strava via their API, and what I hope to do is first, via a button, pull and display a list of recent rides (this part is accomplished) and then once that list is displayed select an individual ride to import. At the moment, it's a bit of an all or nothing scenario where I can extract all ride files at once but I wanted to do it more "on-demand" So what I'm hoping to do is get the portion which collects the streams and make that into it's own function that can receive data from this first rendering function and call upon a single ride stream to add to a model/file/whatever. Just curious to see if someone had any insight on what stuff to explore def stravadownload(request): adict={} actdict={} activitydict={} if "downstrav" in request.POST: client = Client() activity=Activity() with open("stravtoken.json", "r") as stravtoken: tokendict = json.load(stravtoken) access_token = tokendict["access_token"] refresh_token = tokendict["refresh_token"] expires_at = tokendict['expires_at'] client.access_token=access_token client.refresh_access_token= refresh_token … -
Failed to push an app in heroku with python
im trying to deploying an app with python django.. But when i get this error: From my build log in heroku.. -----> Python app detected .... -----> Installing requirements with pip ... Collecting psycopg2==2.6.2 Downloading psycopg2-2.6.2.tar.gz (376 kB) ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-a0nakbaj/psycopg2/pip-egg-info cwd: /tmp/pip-install-a0nakbaj/psycopg2/ Complete output (7 lines): ..... Error: could not determine PostgreSQL version from '12.2' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Here is my requeriments.txt if you need it: colorama==0.4.1 dj-database-url==0.5.0 Django==2.2.1 django-qr-code==1.0.0 gunicorn==19.9.0 Pillow==6.0.0 psycopg2==2.6.2 pytz==2019.1 qrcode==6.1 six==1.12.0 sqlparse==0.3.0 whitenoise==4.1.2 Anyone can help me with whis? Thank you! -
Django: no module named "django_haystack" but here it is, I think
pip3 install django-haystack ... comfortingly says: Successfully installed django-haystack-2.8.1 But then `./manage.py migrate' ... says ModuleNotFoundError: No module named 'django-haystack' In my .virtualenvs/[...]/ I find these directories: django_haystack-2.8.1-py3.6.egg-info haystack ... but pip3 uninstall haystack says Skipping haystack as it is not installed. ... and pip3 uninstall django-haystack is ready to delete the directories aforementioned. Okay, so if pip3 install finds it, what's migrates problem? My INSTALLED_APPS hash includes django-haystack ... -
Multiple database router
The project is about two databases, the first one: default (which I've been working and contains several models) and the second one: customer (it must handle only 1 model). App name: cities Database's names: default and customer Model in customer's db: mail_receiver I've been following some Django's manuals but it doesn't work. The routers that I'm using are: routers.py class defaultRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cities': return db == 'default' return None class customerRouter(object): def db_for_read(self, model, **hints): """ Attempts to read user models go to default. """ if model == 'mail_receiver': return 'customer' return None def db_for_write(self, model, **hints): if model == 'mail_receiver': return 'customer' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name='mail_receiver', **hints): if app_label == 'cities': return db == 'customer' return None settings.py DATABASES = { 'default': { 'NAME':'cities', 'USER': 'root', ... }, … -
Django - model with several tag fields
I need a model with several "tag" fields. For example: class Food(models.Model): type = SomeTagField() manufacturer = SomeTagField() It could be done using many-to-many relationships, but I'm not sure if this is a correct approach. It looks a little bit overcomplicated. I've tried django-tagit and its TaggableManager but without luck: ValueError: You can't have two TaggableManagers with the same through model. What would be a correct way to handle that? -
Django sqlmigrate not showing raw sql
I tried to get the raw sql from Django migrate file. I took the following steps: $ python manage.py makemigrations $ python manage.py sqlmigrate app_name 0001 and raw sql command should display, but the result only contains: BEGIN; -- -- Create model User -- -- -- Create model Config -- COMMIT; How to get the raw sql from sqlmigrate? -
Call function when call another function
I want to call some function from django view. Class view(view): Def get(self): Some stuff... Return httpresponse Def a(): Some stuff I want to call a() function when view is called, without calling a() in view body. Maybe there is any decorator or something else, which helps me with it. Something like: Class view(view): Def get(self): Some stuff from view Return httpresponse @call_with_view Def a(): Some stuff from a >> View() >> some stuff from view >> Some stuff from a -
Django Rest Framework: Custom Forms, Custom JSON output
I have to use Django Rest Framework to develop a form that accepts 2 inputs, customer ID and seat number, and this form is to be limited to 10 customers. My Output JSON should have customer ID, seat number, customer_occupancy (which is 2*customer_id) and total customer occupancy (which is sum of all customer_occupancy values entered up until that point). I've added my code for models.py and views.py down below. I have no idea how to ensure the form doesn't have more than one field for which value is to be entered (seat number) nor why the queryset.update() is not resulting in any change in the output. Any help to resolve this would be much appreciated. models.py: from django.db import models class Hero(models.Model): seat_number = models.CharField(max_length=160, default='No Comment') customer_occupancy = models.IntegerField(default = 0) total_cust_occupancy = models.IntegerField(default = 0) def __int__(self): return self.id views.py: from django.shortcuts import render from rest_framework import viewsets from .serializers import HeroSerializer from .models import Hero global total total = 0 class HeroViewSet(viewsets.ModelViewSet): global total queryset = Hero.objects.all().order_by('id') for idx, i in enumerate(queryset): queryset[idx].customer_occupancy = 2*int(queryset[idx].id) total += queryset[idx].customer_occupancy queryset[idx].total_customer_occupancy = total print(queryset[idx].customer_occupancy) print(total) print(queryset[idx].total_customer_occupancy) queryset.update() serializer_class = HeroSerializer serializers.py: from rest_framework import serializers from .models import Hero … -
Whats the most performant way to reverse a lookup on a dict of tuples?
I have a choices field, with a list of tuples: EVENT_CHOICES = [(1, "queued"), (2, "sent"), (3, "failed")] This is stored as a PositiveSmallIntegerField rather than a CharField for performant reasons: event_type = models.PositiveSmallIntegerField(choices=EVENT_TYPE_CHOICES) In my app, the field is populated by a webhook to an external source, which POSTS the str component of the tuple. E.g. I receive queued, sent, or failed as a POST variable. What's the easiest/most performant way to reverse a lookup on EVENT_CHOICES to return the int from the str? E.g, a clumsy long form way would be: if event == "queued": event_type = 1 if event == "sent": event_type = 2 if event == "failed": event_type = 3 Given I actually have a lot of choices, I assume there has to be a neater way for this? -
I tried to load a web page created with django framework but it give me an error while loading it
[enter image description he][1] To start, I have created a web page containing a form with post method and with csrf_token and I put a button to submit the information, then after clicking the button there is a new page that is apearing, and when I try to load this second page it gives me the error above in the picture. thanks for interesting :) -
django-imagekit throwing AttributeError exception in ImageCacheFile default ctor function
I am working on a project, using the following components: django: v2.2.10 django-podcasting: 1.3.2 django-imagekit: 4.0.2 django-photologue: 3.11 When I try to add a new podcast show, I get the following error message: AttributeError at /admin/podcasting/show/add/ Here is the full stack trace: Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /admin/podcasting/show/add/ Traceback (most recent call last): File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/__init__.py", line 37, in __init__ name = generator.cachefile_name File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 95, in cachefile_name return fn(self) File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/namers.py", line 40, in source_name_as_path '%s%s' % (generator.get_hash(), ext))) File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 134, in get_hash self.source.name, File "/path/to/project/env/lib/python3.6/site-packages/photologue/models.py", line 345, in __getattr__ raise AttributeError AttributeError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1645, in add_view return self.changeform_view(request, None, form_url, extra_context) … -
aws lambda deployed by zappa is not able to connect to remote database
I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database. I'm tring to connect to the database using djongo. I set my django_setting in the zappa_settings.json to my project's django settings. The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST). The actual error I get is: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused The above exception was the direct cause of the following exception: djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT If anyone has an idea I'd would love to hear. attaching the settings with some fields unset (but set at my settings) DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db', 'HOST': 'mongodb://<username>:<password>@<> 'USER': 'username', 'PASSWORD': 'password', } } { "dev": { "aws_region": "eu-west-1", "django_settings": settings, "profile_name": "default", "project_name": name, "runtime": "python3.6", "s3_bucket": bucket, "timeout_seconds": 900, "manage_roles": false, "role_name": name, "role_arn": arn, "slim_handler": true } } -
ORM trouble with Django
I want two lists of books, 1 of books that has already been "liked" by the user aka 'myBooks', and another list of all other books, 'otherBooks'. Instead, I can only get 1 book on the first list (the first one liked) and after that the list doesn't change (it doesn't even disappear from second list which excludes any liked books). I am using the filter command which I know is for multiple, and my queries work fine in shell, and yet in my actual program I only get that single query. def books(request): if 'userid' not in request.session: return redirect('/') else: num = request.session['userid'] thisUser = User.objects.get(id=num) myfavorites = Favorite.objects.filter(user=thisUser) context = { "user" : thisUser, "otherBooks" : Book.objects.exclude(favorites=myfavorites), "myBooks" : Book.objects.filter(favorites=myfavorites) } return render (request, 'app1/books.html', context) -
Django DRF : how change to change Date format in my serializer.py?
I am new to Django DRF and I need a small tip. My Problem : I want to change the standart models.DateField to the following format "%d-%m-%Y". I want to do it for the field "birthday" or in general for the project. I tried in directlty in the model.py with : .... birthday = models.DateField(null=True , input_formats= "%d-%m-%Y" ) but it did not work . .... I also added in the setting.py REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"],} but it did not work. Now i want to try in the serializer.py but given my class I don't know where to do it . My serializer.py looks like that : from rest_framework import serializers from payload.models import Payload class PayloadSerializer(serializers.ModelSerializer): class Meta: model = Payload fields = ['first_name', 'last_name', 'email', 'birthday',] def create(self, validated_data): """ Create and return a new `payload` instance, given the validated data. """ return Payload.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `payload` instance, given the validated data. """ instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.birthday = validated_data.get('birthday',instance.birthday) instance.save() return instance SO the question : Where and how do I change in this class the the format of the … -
How to get the minimum value of an instance of django model
I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows class Hotels(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) mobile_number = models.CharField(max_length=12) created_at = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) description = models.TextField() slug = models.SlugField(unique=True) property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos') star_rating = models.PositiveIntegerField() contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,) class Room(models.Model): hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,) room_photo = models.ImageField(default='default.jpg', upload_to='room_photos') room_Name = models.CharField(max_length = 200) room_details = models.CharField(max_length = 500) room_Capacity = models.PositiveIntegerField(default = 0) slug = models.SlugField(unique=True) # guest_numbers = models.IntegerField(default=0) room_Price= models.PositiveIntegerField(default = 0) total_Rooms = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,) More details From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist -
Loading Django model data into HTML from specific model
When I click on a link on my homepage I want to go to a page with a dynamic URL. I managed this by changing my URLS.py to urls.py urlpatterns = [ path('', views.home, name='home'), path('<str:god_url>', views.godpage, name='godurl'), ] homepage.html <a class="button" href="{{ GodList.god_name }}">Watch now</a> This post is in a for loop, cycling trough godnames. So when clicking on the button above, the god name of that button is added to the url and a new page is loaded. views.py def godpage(request, god_url): godlink = GodList.objects.get(god_link=god_url) context = {'godlink': godlinklink} return render(request, 'my_app/god.html', context) models.py class GodList(models.Model): godName = models.CharField(max_length=50, unique=True) godFoto = models.CharField(max_length=100, unique=True) godlink = models.CharField(max_length=100, unique=True) def __str__(self): return self.godName In this new page I want to load a link which is in the database / models (using postgresql) This link can be found in the same model as the god name that was added to the url. How can I find this link inside of the models and get it in the HTML? <img src="{{ context }}"/></a> -
Django Celery task received, execute, but not finished with GlobalBestPSO pyswarms
I have Django app with Celery in Docker. Have Django container, Celery container. django==1.11.4 gunicorn==19.7.1 celery==4.4 redis==3.4.1 sqlalchemy==1.3.13 raven==6.1.0 requests==2.22.0 numpy==1.13.3 pandas==0.20.3 keras==1.2.1 theano==0.9 scikit-learn==0.18.1 matplotlib==2.1.1 seaborn==0.8.1 salib==1.1.2 pyswarms==1.1.0 deap==1.3.0 In my celery task I have code: from celery import shared_task from pyswarms.single.global_best import GlobalBestPSO @shared_task() def predict_task(): # Some code for i in range( print ('print 111') optimizer = GlobalBestPSO(n_particles=n_part, dimensions=sample_vals.shape[0], \ options=options, bounds=bounds, \ init_pos=positions) print ('print 222') cost, pos = optimizer.optimize(predict_seeded_func, iters=1000, **kwargs) costs.append(cost) poses.append(pos) # Some code Run task with delay function: predict_task.delay(19, test_id, sample_data.to_json()) Then I see, that [2020-03-16 22:26:11,689: INFO/MainProcess] Received task: app.tasks.predict_task[f207ac10-5eb5-464b-aed7-b3ec3d2d029d] [2020-03-16 22:26:11,750: WARNING/ForkPoolWorker-2] print 111 And after then nothing happens. But, if I run without celery delay(): predict_task(19, test_id, sample_data.to_json()) Then code is successfully executed to the end. And I get the result. What can be wrong? Why GlobalBestPSO not executed in task? -
How to correctly localize fields in forms?
I use Django 3.0.4 and Crispy Forms 1.9.0 I have the following model: class App(models.Model): name = models.CharField(max_length=256, db_index=True, verbose_name=_('Name')) platform = models.ForeignKey(Platform, on_delete=models.CASCADE, verbose_name=_('Platform')) package_name = models.CharField(max_length=512, unique=True, verbose_name=_('Package name')) created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name=_('Created Date')) Form: class CreateAppForm(forms.ModelForm): class Meta: model = App fields = ('name', 'platform', 'package_name',) localized_fields = '__all__' # I've tried to enumerate fields as tuple # labels = { # I've tried to uncomment it # 'name': _('Name'), # 'platform': _('Platform'), # 'package_name': _('Package name'), # } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['platform'].queryset = Platform.objects.filter(is_enabled=True) And template: {% extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block title %}{% trans "Create application" %}{% endblock %} {% block page_title %}{% trans "Create application" %}{% endblock %} {% block content %} <div class="row"> <div class="col"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{% trans "Create application" %}</h6> </div> <div class="card-body"> <form class="form" action="{% url 'apps:create' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success btn-lg" type="submit"><i class="fa fa-check"></i> {% trans "Create" %}</button> </form> </div> </div> </div> </div> {% endblock %} All strings in .po files are localized and compiled (and work everywhere but in forms). The … -
How do you effectively cache a large django queryset?
I am working on a Django project using a PostgreSQL database in which I need to run a sometimes complex query on a user profile table with ~1M records, and the dataset returned can be anywhere from 0 to all 1M records. My issue is that once I grab all of the records, I want to be able to filter them further to run analytics on these profiles. The analytics cannot be completed in the same request/response loop, as this will time out for all but the smallest querysets. So I am using async javascript to shoot off new requests for each type of analytics I want. For example, I will grab all of the profiles in the initial request and then i will send subsequent requests to take those profiles and return to me the % of genders or % of users who have a certain job title, etc. The issue is that every subsequent request has to run the original query again. What I would love to do is somehow cache that query and then run my query on this subset of the profile table without having to execute the original, long-running query. I have tried to use … -
what is the difference this two pieces of code
I tried replacing this cood in Django Documentation def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) with this code def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] for q in latest_question_list: output = ', '.join([q.question_text]) return HttpResponse(output) -
How to use date widget in django-import-export?
I'm new to programming so please bear with me in case I ask silly questions. I'm working on my first project which will gather data from Excel file. I'm trying django-import-export for that purpose but ran into a problem with date containing field. As far as I could understand searching this issue I need to use Date widget, cause it basically reads it as string while importing. But I couldn't find any example where this widget is used so I can see it's syntax. The model I'm working on is shown below. Hope some of you can help me on this. Thanks. from django.db import models from import_export.admin import ImportExportModelAdmin from import_export import widgets class Employee(models.Model): name = models.CharField(max_length=200) badge = models.CharField(max_length=15) start_date = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=True,widget=widgets.DateWidget(format=None)) end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) status = models.BooleanField(choices=( (True, 'Active'), (False, 'Inactive') ), default=True) job = models.ForeignKey(Matrix, on_delete=models.CASCADE, blank=True, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.badge)+ str(" - ") + str(self.name) class Meta: ordering=('name', 'badge', 'start_date', 'status',) verbose_name='Employee' verbose_name_plural='Employees' -
Send email using django without a settings file
Is it possible to do something like the following using the utility django sendmail? >>> import os >>> from django.core.mail import send_mail >>> os.environ['EMAIL_HOST'] = 'smtp.sendgrid.net' ... etc. >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'from@example.com', ... ['to@example.com'], ... fail_silently=False, ... ) django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If so, how could I do this? -
Django admin page. When i run the server everything will be fine, but when i try log into the admin page i will lose my connection
Am getting back the last line after i navigate to the 127.0.0.1:8000/admin the browser message This site can’t be reached127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED my terminal message "C:\Program Files\JetBrains\PyCharm 2019.2\bin\runnerw64.exe" C:\Users\UCHE\PycharmProjects\blog\venv\Scripts\python.exe C:/Users/UCHE/PycharmProjects/blog/manage.py runserver 8000 Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). March 16, 2020 - 22:15:50 Django version 3.0.4, using settings 'blog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [16/Mar/2020 22:16:26] "GET / HTTP/1.1" 200 19 Not Found: /favicon.ico [16/Mar/2020 22:16:28] "GET /favicon.ico HTTP/1.1" 404 2136 [16/Mar/2020 22:16:34] "GET /admin/ HTTP/1.1" 302 0 [16/Mar/2020 22:16:34] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [16/Mar/2020 22:16:35] "GET /static/admin/css/base.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/login.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:49] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Process finished with exit code -1