Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to store excel file into django models genrating from pandas operation
I want to store an excel file created from pandas dataframe into django models but when I save it an entity create into models but no file exist Models.py class TaskResult(models.Model): result_file = models.FileField(blank=False, null=False) def __str__(self): return self.result_file.name views.py def handle_uploaded_file(request): file_obj = excelFile.objects.all().order_by('-id')[0] excel = file_obj.file.read() data_1 = pd.read_excel(excel) data_1 = data_1.dropna() Acceptence = data_1['Accepted Compound ID'] index_PC = Acceptence.str.endswith('PC') index_LPC = Acceptence.str.endswith('LPC') index_plasmalogen = Acceptence.str.endswith('plasmalogen') data_LPC = data_1.loc[index_LPC] task_obj = taskResult() task_obj.result_file = data_LPC.to_excel('data_LPC.xlsx') task_obj.save() -
how to generate token in login api view for authentication in django?
This is my user login view. I want to know the command that will automatically generate the token for that user after logging in, so that I can logout that user deleting that token later. class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data=serializer.data return response.Response(new_data, status=status.HTTP_200_OK) return response.Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) In my settings. INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } This is my serializers: class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): user_obj = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") user = User.objects.filter(Q(email=email)).distinct() if user.exists() and user.count() ==1: user_obj = user.first() else: raise serializers.ValidationError("This email is not valid/already exists") if user_obj: if not user_obj.check_password(password): raise serializers.ValidationError("Incorrect password") return data -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine in django
I am trying to implement email in an django application using sendgrid. Whenever I try to send email I run into the below exception. winerror 10053 an established connection was aborted by the software in your host machine I am using windows 10, python 3.7.6 and django 3.0.8. -
Can't run django project in docker
when im running docker it stucks on this part: Recreating payments_app_1 ... Recreating payments_app_1 ... done Attaching to payments_app_1 app_1 | Watching for file changes with StatReloader Dockerfile FROM python:3.6 ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./app /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["python","manage.py","runserver"] docker-compose version: '3.3' services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 requirements.txt Django==3.1.2 -
Django Dictionary data in Dictionary how to get in single dictionary
I am new to this django and i come to a solution to this problem please help This is how my data is coming { "total_revenue": { "plan_id__plan_price__sum": 363 }, "thirty_days_revenue": { "plan_id__plan_price__sum": 363 }, "last_year_sale": { "plan_id__plan_price__sum": 363 } } I want my data to be like this { "total_revenue" : 363, "thirty_days_revenue": 363, "last_year_sale": 363 } My serializer is this: @staticmethod def get_total_revenue(self): total_revenue = self.aggregate(Sum('plan_id__plan_price')) return total_revenue @staticmethod def get_thirty_days_revenue(self): today_date = datetime.datetime.today() last_month = datetime.timedelta(days=30) date = (today_date - last_month) revenue = self.filter(created_on__range=(date, today_date)).aggregate(Sum('plan_id__plan_price')) return revenue @staticmethod def get_last_year_sale(self): today_date = datetime.datetime.today() last_month = datetime.timedelta(days=365) date = (today_date - last_month) revenue = self.filter(created_on__range=(date, today_date)).aggregate(Sum('plan_id__plan_price')) return revenue -
Python3 Django REST Framework, what's the best way to run a task in 2020?
Lately I have been building a REST API from the ground up. I eventually want to add endpoints that will trigger a task to run. So I have endpoints that are resources (ie 0.0.0.0/todos/1) and allow CRUD operations, and eventually endpoints that will be hit to execute tasks (ie 0.0.0.0/run_task_for_todo) I have looked into celery and redis and it looks promising. But is there a better way to do this on AWS? I know the basics of AWS EC2, but that is only scratching the surface... I was thinking about using AWS Lambda to serve the REST API, and possibly AWS SQS for the task queue... then have (maybe?) an ec2 instance that constantly polls the AWS SQS, and based on the incoming events execute the task? This might not even be the correct place to post this question but I figured I'd give it a shot here first. Thanks to all of those who reply in advance! -
Why the Models not showing up in django website
I am making a news website and i have made a model of an image, title, description,url(for clickable image), but the final output is not just showing up and there is no error . Please also look into image links I have attached The output Screenshot and The admin Page screenshot The output AdminPage Screenshot Main Code <div class="col-lg-9 stretch-card grid-margin"> <div class="card"> <div class="card-body"> {% for Flash in flashes %} <div class="row"> <div class="col-sm-4 grid-margin"> <div class="position-relative"> <div class="rotate-img"> {% if Flash.url %} <a href="{{ Flash.url }}"> <img src="{{ project.image.url }}" alt="thumb" class="img-fluid" /> </a> {% else %} <img src="{{ project.image.url }}" alt="thumb" class="img-fluid" /> {% endif %} </div> <div class="badge-positioned"> <span class="badge badge-danger font-weight-bold" >Flash news</span > </div> </div> </div> <div class="col-sm-8 grid-margin"> <h2 class="mb-2 font-weight-600"> {{ Flash.title }} </h2> <div class="fs-13 mb-2"> <span class="mr-2">Photo </span>10 Minutes ago </div> <p class="mb-0"> {{ Flash.description }} </p> </div> </div> {% endfor %} {% endblock %} </div> </div> </div> Views.py from django.shortcuts import render from .models import AllProject from .models import Flash def techhome(request): allprojects = AllProject.objects.all() return render(request, 'techworld/techhome.html', {'allprojects':allprojects}) def Flashnews(request): flashes = Flash.objects.all() return render(request, 'techworld/techhome1.html', {'flashes':flashes}) Models.py from django.db import models class AllProject(models.Model): title = models.CharField(max_length=100) description … -
I just connect my mongodb with django but It did't work
I am trying to connect mongodb with django, everything looks correct but it did not create a default table for me. when I makemigrations and migrate I got this. enter image description here but It did not create anything to my database, How can't I check the connection or what I was wrong :( -
how to access google spreadsheet json file from s3 while using aws lambda with django
I am using django and deployed my application on aws_lambda. Everything worked fine until i wanted to save the content of the database in a google spreadsheet The problem is how to access/get the json.file (that would normally be located in the same folder as where i am using it) now that i am aws_lambda in production views.py scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name("secret-json-file.json", scope) gc = gspread.authorize(credentials) open_google_spreadsheet = gc.open('data').sheet1 but since i am using aws_lambda and i stored that json on the main folder of aws s3 I am trying something like this s3_client = boto3.client("s3") response = s3_client.get_object(Bucket=aws_bucket, Key="secret-json-file.json") data = response["Body"].read() # Google spreadsheet scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(data, scope) I also tried this approach: AWS_ID = aws_access_key_id AWS_KEY = aws_secret_access_key AWS_S3_BUCKET = secrets.aws_bucket session = boto3.session.Session(aws_access_key_id=AWS_ID, aws_secret_access_key=AWS_KEY) s3 = session.resource("s3") my_s3_bucket = s3.Bucket(AWS_S3_BUCKET) current_s3_file = [] for s3_file in my_s3_bucket.objects.all(): if s3_file.key == "secret-json-file.json": current_s3_file.append(s3_file) # Google spreadsheet scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(current_s3_file, scope) Unfortunately both approaches are not successful. Any help would be much appreciated -
Get form value on Inline
I'm working with the Django administrator, I have a SampleAdmin with an Inline Order inside, in which I need to filter records in the latter depending on what is selected in the SampleAdmin (that is, a nested field or nested selects) So far I have this in admin.py: class SampleAdmin(admin.ModelAdmin): list_display = ('number', 'sample', 'date', 'acept') fields = (('matrix', 'type_sample'),('sample')) inlines = (OrderInline,) ------------------------------------------------------------------------------------------------ class OrderInline(admin.TabularInline): model = Result fields = ('assay',) def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field.name == "assay": kwargs["queryset"] = Assay.objects.filter(matrix_id=3) return super(OrderInline, self).formfield_for_foreignkey(db_field, request, **kwargs) Where the number 3 is found, I would like to place the ID value of the matrix field of SampleAdmin. From already thank you very much, greetings -
Django: Including a view in another view and running the subviews GET method
If I have a view (FruitObservations) that is rendering a template, and I'm trying to access another view (UpdateFruitObservations) via include, is there a way I can provoke the included view to do more than show its templated HTML, and actually run its GET method? It's showing the included HTML just fine, but refuses to render an included formset through the running of the GET method, it seems. I just get the rendered written HTML (no form) but the id renders in the HTML text. {% include "./update_fruit_observation.html" with fruit_id=fruit.id %} I should also mention that I'm rendering the subview's HTML as a bootstrap 4 modal, if that matters, and opening the modal via jQuery. Also, there is no network request running to the 'update-fruit-observation' URL -
Firebase Admin SDK vs fcm-django
I'm developing mobile backend using Django. I need to send remote push notifications to iOS device using Firebase Cloud Messaging. It seems I have two options. 1. Use Firebase Admin SDK, 2. fcm-django. There are little info about those on web so I'm wondering which one is better. What are pros and cons of using those frameworks and which should I use? -
Writable nested serializers with inherited django models
I'm struggling to update records with the writeable nested serializers I've created. There are many Listing categories for a classifieds app I'm creating that each have a few unique attributes, but they also share many attributes. I have a handful of django models that inherit from a parent Listing model, and one of these models, Battery, contains some nested data. So far I've been able to create Battery records but keep getting AttributeErrors when I try to update them. I've tried to include only the relevant code. Here are my views: # views.py class ListingCreateView(CreateAPIView): queryset = Listing.objects.all() def get_serializer_class(self): category = self.request.data['category'] if category == 1: return PercussionSerializer elif category == 6: return BatterySerializer return ListingSerializer class ListingUpdateView(UpdateAPIView): queryset = Listing.objects.all() def get_serializer_class(self): category = self.request.data['category'] if category == 1: return PercussionSerializer elif category == 6: return BatterySerializer return ListingSerializer here are my models: # models.py ## Parent model class Listing(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True, default=0.00) ## One of the child models class Battery(Listing): model_name = models.TextField(blank=True, null=True, default="") color = models.ForeignKey(Color, on_delete=models.CASCADE, blank=True, null=True) manufacture_year = models.IntegerField(null=True) ## Model for the nested data in Battery model class Drum(models.Model): drum_type = … -
Use production media files in development - Django
I have a blog made with Django (and Django-CMS). Some times, when working in development, I make some changes and it would be nice to see how those changes that I'm doing look like with the actual media files that I have in production. So today I tried to set the MEDIA_URL and the MEDIA_ROOT settings to be the actual media URL of my production site. i.e: MEDIA_URL = 'https://example.com/media/' MEDIA_ROOT = 'https://example.com/media/' I was naively hoping to see the media files of production in development after doing this, but nope, it didn't work. Aditional info: My site is hosted by PythonAnywhere, and they (pythonanywhere) serve the media files as well. The files are all public. I use django-filer as my file manager. One sample of my media files: media file Anyway, is this possible to achieve? If so, what am I missing? -
build a function helper for dynamically upload file
before all , I hope you guys are in the very good and healthy conditions ! hi, I want to make all the uploaded files will be uploaded to the dynamically named file that's related to the name of it's model name this is the functions I've created to be put on the upload_to= arguments in imageField def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) for i in range(length))) return result_str def namefile_profile_picture(instance, filename): ext = filename.split('.')[-1] get_random_1 = get_random_alphanumeric_string(10) get_random_2 = get_random_alphanumeric_string(10) name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2) filename = "%s.%s" % (name_of_file, ext) return 'user_{}/{}/{}'.format(instance.user.username,'profile_picture',filename) def namefile_poster_picture(instance, filename): ext = filename.split('.')[-1] get_random_1 = get_random_alphanumeric_string(10) get_random_2 = get_random_alphanumeric_string(10) name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2) filename = "%s.%s" % (name_of_file, ext) return 'user_{}/{}/{}'.format(instance.user.username,'poster_picture',filename) def namefile_photo(instance, filename): ext = filename.split('.')[-1] get_random_1 = get_random_alphanumeric_string(10) get_random_2 = get_random_alphanumeric_string(10) name_of_file = "{}{}{}".format(get_random_1,str(instance.id),get_random_2) filename = "%s.%s" % (name_of_file, ext) return 'user_{}/{}/{}'.format(instance.user.username,'photo',filename) so instead of manually using these functions for every different imageField such as class Photo(models.Model)`: ... image = models.ImageField(upload_to=namefile_photo) ... class Profile(models.Model): ... image = models.ImageField(upload_to=namefile_profile_picture) ... I wish there is a way to create such a one function or class that can perform such example above the way which I can just easily pass some name file … -
Django RuntimeError when using models for unittests
I'm using multiple models for running tests like this one on a django-2.2 project: class Person(models.Model): name = models.CharField(max_length=200) Running a simple test: class TestRegistration(SimpleTestCase): def setUp(self): self.site = admin.AdminSite() def test_bare_registration(self): self.site.register(Person) self.assertIsInstance(self.site._registry[Person], admin.ModelAdmin) But always getting the same kind of RuntimeError, with this one as with other models (the model raised changes but the RuntimeError persists): "INSTALLED_APPS." % (module, name) RuntimeError: Model class tests.models.Person doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've already tried: Deleting the init.py Deleting the content of the init.py Explicit import the model from the init.py importing the model from inside the function as this article suggessts ( https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a ) Running the tests with django-nose Declaring the model from the same test Setting a test-env with the same settings but adding the models Running the tests not only with -c"python manage.py test", also with a "python runtest.py" as suggessts in ( https://docs.djangoproject.com/en/3.1/topics/testing/advanced/ ) Here is the complete message error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/codea/Workspace/venv3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/codea/Workspace/venv3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/codea/Workspace/venv3.6/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/codea/Workspace/venv3.6/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, … -
How to send error messages from Django ModelForm clean_<name> method to view?
I have the following ModelForm: class AddObjForm(forms.ModelForm): # stuff ... def clean_performed_by(self): # validation for performed_by if not valid: e = "Error message I want to send back to view" raise forms.ValidationError(e) return performed_by I have the following view: class AddObject(LoginRequiredMixin, CreateView): # stuff ... def post(self, request, *args, **kwargs): form = AddObjForm(request.POST) if form.is_valid(): messages.success(request, f"New obj created: {new_obj}") return HttpResponseREdirect("whatever") else: messages.error("?") # How do I get my error message from my form into my view? return(request, template, context) My question is how do I get the error message I raised in my ModelForm into my view so that I can put it into the messages.error() method? I found code resembling this, but I can't find how to access/update form.error_messages in the documentation: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") -
Beginner Django / Python / Postgres dev struggling with no model data output to html file
I have been working through some basic online Youtube tutorials for Django, which have been great, but I've been struggling the last few days with my Test-table app, being unable to display table data on my example Postgresql table placed on my index.html file. When I created the Postgres model (local hosted), it appears correctly with data in the admin page, and my index page loads successfully from my url and view file configurations, but is missing the table data specifically and I'm hoping for some guidance on what I am doing incorrectly. I understand there are more dynamic configurations for the URL and views, but I was attempting to get a basic one working first... models.py file: from django.db import models class products(models.Model): Phone = models.TextField(primary_key=True) Version = models.TextField(max_length=100) Price = models.FloatField() Sales = models.IntegerField() class Meta: db_table = "productlist" Url file: from django.contrib import admin from django.urls import path from . import views app_name = 'Test_table' urlpatterns = [ path('admin/', admin.site.urls), path('', views.sales), ] views.py from django.shortcuts import render from Test_table.models import products # from django.http import HttpResponse def sales(request): ph_data = products.objects.all(), return render(request, 'Test_table/index.html', {'ph_data': ph_data}) html file: <table border='3'> <tr> <th>Phone</th> <th>Version</th> <th>Price</th> <th>Sales</th> </tr> … -
Proper way to insert DJANGO tag into tag?
I want to write an href call passing the parameters through a DJANGO tag, something like : <a href="{% url 'incid:vercosas' filtro='cerradas' vista={{ vista }} %}" to replace this: <a href="{% url 'incid:vercosas' filtro='activas' vista='tabla' %}" when {{vista}} holds the value 'tabla, but I only get this message: Reverse for 'vercosas' with keyword arguments '{'filtro': 'cerradas', 'vista': '{{ vista }}'}' not found. 1 pattern(s) tried: ['incid/vercosas/(?P\w+)/(?P\w+)/$'] from PyCharm. What would be the proper way to do this? -
Django: Is there a way to use admin to add image files to an app's static DIR?
So I'm not sure if this is a terrible setup, but here it is. I created a basic portfolio app in Django with the help of a tutorial. However I wanted to be able to add the portfolio entries in admin. I use the following function in "projects/models.py" class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=100) image = models.ImageField(upload_to='**PATH**') If I use the string projects/static/img/ as the PATH, the files go where I want. However, then I cannot access them in the template with either "{{project.image.url}}" or "{% static project.image.url%}" If I use MEDIA_ROOT and then img/ as the PATH, the files (obviously) go to media/img/, then I can access them with "{{project.image.url}}". However, then this does not collect in staticfiles using collectstatic and thus is unsuitable for production. Is there a way to add my files directly to projects/static/img/ in admin while still allowing me to access them in the html template? -
How to recover from Django Channels connection limit?
I'm running a server on heroku where I have intermittent channel layer communications between instances of asyncConsumers. Running heroku locally, I have no problem with redis channel connection since I can have as many of them as I want, but once I upload my server to heroku, it gives me a 20 redis connection limit. If I use more than that my server errors out, so I try to lower the expiry time so inactive redis connections would close. BUT, if a redis connection expires and I try to use the channel name with self.channel_layer.send(), I'll get the error below, how do I recover from this error without having to have external calls to create another asyncConsumer instance? ERROR Exception inside application: Reader at end of file File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/app/.heroku/python/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "./myapp/webhook.py", line 133, in http_request await self.channel_layer.send(userDB.backEndChannelName,{"type": "device.query"}) File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 296, in send if await connection.llen(channel_key) >= self.get_capacity(channel): File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/list.py", line 70, in llen return self.execute(b'LLEN', key) File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 51, in execute return self._pool_or_conn.execute(command, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/connection.py", line 322, in execute raise ConnectionClosedError(msg) Reader … -
Override Field Option on Inherited Modl in Django
I've found similar questions and answers, but none seems exactly right. I've got an abstract base model like so: class BaseModel(models.Model): timestamp = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) description = models.CharField(max_length=512, blank=True, null=True, help_text='Help') class Meta: abstract = True And then I'm inheriting from it: class AnotherModel(BaseModel): field1 = models.CharField(max_length=512) But I want this model's help_text on the description field to be something else, like help_text='Some other help text' What's the best way to do this? Can I override options on fields from inherited models? -
Why am I losing access to context after invalid form submission?
So, I have a URL pattern: path('<int:pk>/<slug:slug>/', PostDetailView.as_view(), name='detail') I have a view: class PostCommentView(CustomLoginRequiredMixin,CreateView): template_name = 'blog/comment.html' model = Comment form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = get_object_or_404(Post, pk = self.kwargs.get('pk')) return context def post(self, request,pk,slug): if request.method == "POST": form = self.form_class(request.POST) post = get_object_or_404(Post, pk=pk) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() messages.success(request, (request, 'blog/post_detail.html', {'form': form, 'slug': post.slug, 'pk': post.id, 'username': post.author})) return redirect('/' + str(post.id) +'/' + str(post.slug) + '/' +'#comment') return render(request, 'blog/comment.html', {'form': form}) I have a comment model: class Comment(models.Model): title = models.CharField(max_length = 49,) body = models.CharField(max_length = 250) post = models.ForeignKey(Post,on_delete=models.CASCADE) comment_date = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete= models.CASCADE) class Meta: ordering = ["comment_date"] def __str__(self): return self.title The default User model and the Post model: class Post(models.Model): title = models.CharField(max_length = 49) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete= models.CASCADE, default = 'NicholasPolino') slug = models.SlugField(max_length = 250, null = True, blank = False) category = models.ForeignKey(Category, default= 'programming', on_delete=models.PROTECT) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs ={ 'slug': self.slug, 'pk':self.pk}) I have a comment form: class CommentForm(forms.ModelForm): body = forms.CharField() … -
Hiding Postgresql credentials in django
I'm new to programming and I'm having a hard time with something. I've been able to be somewhat make this work. I've created an .env file with this info DATABASE_NAME=db_name DATABASE_USER=db_user DATABASE_PASSWORD=password DATABASE_HOST=localhost DATABASE_PORT=5432 and added this to my settings.py import environ env = environ.Env() environ.Env.read_env() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DATABASE_NAME"), 'USER': env("DATABASE_USER"), 'PASSWORD': env("DATABASE_PASSWORD"), 'HOST': env("DATABASE_HOST"), 'PORT': env("DATABASE_PORT"), } } and it works finest first, I can start the server and migrate files however after I git init and add my .env file to my .gitignore file, Django isn't able to read the file or something and I'm no longer able to start the server.... Also i've tried every other thing you could think of. I've tried decouple i've tried importing from os with credentials put in a .bash_profile file. I've tried literally everything you can find when you google how to hide database credentials using environmental variables. Does anyone know what else could be happening that I am unaware of? -
Is there a way to delete the File from FileField without removing it from S3 with Django Storages?
I have a Django application that is strictly the backend to my frontend application. I use a FileField to upload files that can be downloaded later. I use django-storages to upload to AWS S3. Currently, it saves to the media/ folder while also uploading to S3. To save on disk space, I would like to just have the S3 link. Is there a way to remove just the file from the local hard disk and just have the S3 link?