Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Whitenoise doesn't seem to help images to show up in heroku
this is my tree of directory directory1 | |-- manage.py | |-- build/ | | | |--static/ | . | . | |-- static/ . | . |--images/ . . . . The iamges that I want to see are in directory1/static/images/. setting INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', ... ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', .... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') whitenoise vesrion is 5.2.0. I deployed this app to heroku. everything works fine except images. Do I miss something? Thank you in advance! :) -
Django REST Framework User Registration Privacy Issue: Looking for best practice to not show exception if user with given email exists already
I am suprised I have not found anything on the web regarding the following issue which I thought should be common? I may just have used the wrong search terms so I am happy to receive links with more info. My problem is that when using ACCOUNT_EMAIL_VERIFICATION = 'mandatory' I want to not give a clue to any user except the owner of an email address whether that mail is registered on my website, i. e. not show a "A user is already registered with this e-mail address." if an existing email is entered. My assumption is that that would require for the registration endpoint to return the same response independent of whether the email exists or not. I see several possible approaches, but none seems to be a good one: Use a custom exception handler to remove the exception in question from the error messages sent. That means I have to somehow identify the abovementioned exception among all error messages sent so I can still keep the others in the response. I guess I have to identify the exception message by a string the actual error message (possibly dependent on language settings?). If there are multiple error messages I … -
Connect to Django Admin over SSH using Apache and Port Forwarding
I would like to be able to restrict access to the Django admin for all requests, except for requests that come from inside the server, after connecting via SSH (which I have set as the default on my Ubuntu server) using port forwarding. I am using Ubuntu OS, and Apache server to serve my Django app with a React front-end here. I came across a wonderful description of how to do this with Nginx here. I also saw that it is possible to use <Location> blocks to restrict access to a URI. Can someone please assist here? -
Empty querydict request.data using Django Rest Framework
I am using Django REST Framework, and I use a post request but I have some troubles... I mean when I send this using the parameter Media Type : application/json : { 'name': 'List', 'comment': 'test', 'description': '', 'renders': [ 'application/json', 'text/html' ], 'parses': [ 'application/json', 'application/x-www-form-urlencoded', 'multipart/form-data' ] } It works very well. But when I send that : { 'name': 'List', 'comment': 'test', 'description': '', 'times': [{ 'start': '2020-11-10T14:00:00Z', 'end': '2020-11-10T20:00:00Z', }], 'renders': [ 'application/json', 'text/html' ], 'parses': [ 'application/json', 'application/x-www-form-urlencoded', 'multipart/form-data' ] } I got an empty querydict for the request.data. Could you help me please ? Thank you very much ! -
CSRF cookie not set Django cross-site iframe in chrome
I'm trying to use an iframe of my django site in a different domain, however whenever I submit a form, It says the CSRF cookies is not set. This occurs in chrome and safari. I am running Django 3.1.0. I've tried adding the following settings in my settings.py: SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = [ 'otherdomain.com', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] Further, I can confirm the csrf token is being set in the form using: {% csrf_token %} Lastly, I've also added the @xframe_options_exempt decorator to the form page. Unfortunately the csrf exempt decorator is not an option for me. I've tried clearing my cookies, though it does not solve my problem. Any help would be greatly appreciated! -
Django add User and Listing model to a Watchlist model
I'm trying to add a Listing model for an eCommerce app to a Wishlist model, but I'm not quite sure where I'm going wrong. I referenced this post in order to create a Wishlist model and link it to my User and Listing models via a Foreign key for each. Wishlist post urls.py from django.urls import path from . import views app_name = "auctions" urlpatterns = [ # Listing paths path("", views.index, name="index"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("register/", views.register, name="register"), path("addlisting/", views.add_listing, name="add_listing"), path("viewlisting/<int:listing_id>", views.view_listing, name="view_listing"), # Watchlist paths path("watchlist_add/<int:listing_id>", views.watchlist_add, name="watchlist_add"), ] models.py from django.contrib.auth.models import AbstractUser from django.db import models from datetime import datetime # Categories categories = [ ('misc', 'misc'), ('computers','computers'), ('toys','toys'), ('pets','pets'), ('beauty','beauty'), ('video games','video games'), ('food','food'), ('clothing','clothing'), ] ACTIVE_CHOICES = [ ('Yes', 'Yes'), ('No', 'No'), ] class User(AbstractUser): pass class Listing(models.Model): listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") listing_title = models.CharField(max_length=100) listing_description = models.TextField(max_length=1200) listing_img = models.URLField(null=True, blank=True, max_length=250) created_on = models.DateTimeField(auto_now=True) starting_price = models.DecimalField(decimal_places=2, max_digits=10, default=1.00) # From above categories list category = models.CharField(max_length=30, choices=categories, default='misc') # From active or inactive list active_flag = models.CharField(max_length=10, choices=ACTIVE_CHOICES, default="Yes", verbose_name="active listing") class Meta: ordering = ['-created_on'] def __str__(self): return f"Name: {self.listing_title}, Price: ${self.starting_price}, Posted By: {self.listing_owner}" … -
SynchronousOnlyOperation error when upgrading from python 3.6 to python 3.7 using django channels
I've been attempting to upgrade python from 3.6 to 3.7 for our Django & Django channels application. With that change, Django throws a SynchronousOnlyOperation anytime any HTTP request is made (even if it has nothing to do with websockets). My guess is that somehow the python upgrade has made the Django check more strict. I believe that django channels is serving both the HTTP requests and websocket requests so it expects all code to be async compliant. How do I get Django channels runserver to run the wsgi app synchronously, while the channel consumers asynchronously. # project/asgi.py application = ProtocolTypeRouter({"http": get_asgi_application(), "websocket": routing}) # project/wsgi.py application = get_wsgi_application() Stacktrace: It's clear to me that the auth middleware that is running for a normal wsgi view is not async compliant, how can I get it to run in a sync environment? ERROR Internal Server Error: /a/api Traceback (most recent call last): File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 233, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/___/___/___/___/apps/core/middleware.py", line 60, in __call__ request.is_user_verified = request.user.is_verified() File "/___/___/.pyenv/versions/pd37/lib/python3.7/site-packages/django/utils/functional.py", line … -
Django Multiple table to authentication
I'd like to have 3 differents table and use them to authenticate. Here is my "class diagram" (User Class is the default Django Class): Here is my models: class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) address = models.ForeignKey( Address, on_delete=models.CASCADE, blank=True, null=True ) email = models.CharField(blank=True, null=True, max_length=140) mobile = models.CharField(max_length=12, unique=True) password = models.CharField(max_length=128) optin_email = models.BooleanField(default=False) optin_sms = models.BooleanField(default=False) class ChainStore(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) password = models.CharField(max_length=64) last_login = models.DateTimeField(blank=True, null=True) rules = models.JSONField(default=dict) I've tried to use inheritance with AbstractBaseUser but i had problems like auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'Contact.groups' My Forms: class ContactSignUp(forms.Form): first_name = forms.CharField(max_length=10) last_name = forms.CharField(max_length=10) email = forms.EmailField() mobile = forms.RegexField(max_length=12) password = forms.CharField(max_length=32) password_verification = forms.CharField(max_length=32) class ContactAuth(forms.Form): mobile = forms.CharField(max_length=12) password = forms.CharField(max_length=32) My views: class ContactSignUpView(FormView): form_class = ContactSignUp model = Contact template_name = "sign_up.html" success_url = "/" def form_valid(self, form): """This method is called when valid form data has been POSTed.""" Contact( first_name=form.cleaned_data["first_name"], last_name=form.cleaned_data["last_name"], email=form.cleaned_data["email"], mobile=form.cleaned_data["mobile"], password=form.cleaned_data["password"] ).save() return super().form_valid(form) class ContactAuthView(FormView): form_class = forms.ContactAuth model = Contact template_name = "auth.html" success_url = "/" def form_valid(self, form): """This method is called when valid form data … -
Is there a way to list the column properties of my PostgreSQL tables?
I'm working in a Django project utilizing an old database from the project. The problem is: Migrating with Django don't give me a good fresh database, some fields that should be nullable are not, some are missing, and this breaks the site. The old database is missing some fields too. I need to compare the old database with the new one, but since there are almost 70 tables and lots of columns, I was hoping there is a way to let me visualize this in a easier way... Any ideas? -
How to Convert UTC Time To User's Local Time in Django
I undrestand that this question is repeated, but unfortunately I cannot find any answer. My impression is that Django already takes care of converting server time to local user as long as I have TIME_ZONE = 'UTC' USE_TZ = True in my settings. Even more if the db is postgresql that setting also doesn't matter and every thing will be still converted. however I tried all the followings: {% load tz %} {{ obj.date }} {{ obj.date|localtime }} {{ obj.date | timezone:"Canada/Mountain" }} and only last one works and the rest gives me UTC time. Last one also is not useful as the time would be only correct for users in that zone. I was wondering if I am missing anything here. I have a very simple test model: class TimeObject(models.Model): date = models.DateTimeField(auto_now=True) -
django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases
I'm creating multiple types of users with different permissions and hierarchy by extending AbstractBaseUser in django 3.1. All users are Employee, and there is an exploitation administrator type who is a kind of superuser, a Supervisor who has multiple Drivers under his control and there is a controller who is a independent User. But I get an errors about the models that I used. this is my models definition in models.py: from django.db import models from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.gis.db import models as gis_models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import EmployeeManager class Employee(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=128, blank=False, null=False) last_name = models.CharField(max_length=128, blank=False, null=False) registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False) email = models.EmailField() cni = models.CharField(max_length=18, blank=True) picture = models.ImageField(upload_to='DriversPictures/', max_length=100, blank=True) matricule_cnss = models.PositiveIntegerField(blank=True) driving_licence = models.PositiveIntegerField(blank=True) recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) phone = PhoneNumberField(blank=True, help_text='numéro de telephone') adress = models.CharField(max_length=128, blank=True) city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL) # user = models.OneToOneField(User, on_delete=models.CASCADE) # roles = models.ManyToManyField('Role') is_exploitation_admin = models.BooleanField(default=False) is_supervisor = models.BooleanField(default=False) is_controlor = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) is_active = models.BooleanField(default=True) vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL) USERNAME_FIELD = 'registration_number' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] objects … -
Django REST Framework - Migrate fails when splitting serializers
I'm trying to split the models, serializers and views of my app to get small, readable files. So, I moved from this: app/ recipes/ migrations/ models.py serializers.py views.py To this: app/ recipes/ migrations/ models/ __init__.py tag.py serializers/ __init__.py tag.py views/ __init__.py tag.py Somehow, everything was working fine until I restarted Docker. Then, I realised python manage.py migrate couldn't handle this split, and fails with this error: + python manage.py migrate Traceback (most recent call last): File "manage.py", line 27, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 48, … -
Adjusting images in django
I am working on a django website, the code works pretty well but I'd like to make a few adjustments in order to make the web more professional. There's a section in the web called latest posts. Here's the code: <!-- Latest Posts --> <section class="latest-posts"> <div class="container"> <header> <h2>Latest from the blog</h2> <p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </header> <div class="row"> {% for obj in latest %} <div class="post col-md-4"> <div class="post-thumbnail"><a href="#"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div> <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date">{{ obj.date }}</div> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> </div><a href="#"> <h3 class="h4">{{ obj.title }}</h3></a> <p class="text-muted">{{ obj.overview }}</p> </div> </div> {% endfor %} </div> </div> </section> What you can see in the website is this: As you might have noticed, the images aren't adjusted and therefore, the text doesn't look aligned. Is there any code that can adjust this? -
django Count show different value after search
I simulate Instagram app. I have Followers, Actions models. Each action is done on a "follower". Many actions can point to one follower. class Follower(models.Model): identifier = models.BigIntegerField( _("identifier"), unique=True, null=False, blank=False) class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, ) # django user that performed the action is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back Admin panel: # Custom Admin for Follower model class FollowerAdmin(AdminAdvancedFiltersMixin, NumericFilterModelAdmin, SpecialActions): ... # Private method to count been_followed_counter def _get_been_followed_count(self, obj): return obj.been_followed_count _get_been_followed_count.short_description = 'Been Followed Count' _get_been_followed_count.admin_order_field = 'been_followed_count' # Private method to count follow_back_count def _get_follow_back_count(self, obj): return obj.follow_back_count _get_follow_back_count.short_description = 'Follow Back Count' _get_follow_back_count.admin_order_field = 'follow_back_count' I then override the get_queryset for followers: # Override queryset method to add count's def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( been_followed_count=Count('actionmodel', filter=Q(actionmodel__user=request.user)) ).annotate( follow_back_count=Count( 'actionmodel', filter=Q(actionmodel__user=request.user) & Q(actionmodel__is_followed_back=True) ) ) I get really strange results in the admin panel: no search in panel USERNAME : lior___shahar BEEN FOLLOWED COUNT:5 FOLLOW BACK COUNT:5 This is the True VALUE in actions: Value in action But once I do SEARCH in FOLLOWERS for the username: After Search USERNAME : … -
Could someone please explain to me how much memory this algorithm uses?
userzip = userlocation.objects.get(userid=request.user.id) isstaff = User.objects.filter(is_staff=True) for x in isstaff: for y in userzip: if x.id == y.userid: trainers = isstaff return render(request, "trainerSearch.html", {'trainers':trainers}) I don't really understand space complexity and need to figure it out for this algorithm. An explanation would really be appreciated. I have been trying to figure it out for a while now and feel lost. -
My django project not finding the new app
There's this problem am having right now where there's no error in my code and yet the code won't run. Am still a newbie trying out something I developed a little django project and pushed to github, went to my pythonanywhere console and cloned it. Now I went back to console and created a new app ( startapp command) added to INSTALLED_APPS and added some lines of code in the new app. Problem is that the URLs in the new are not going through and even the ls command is not listing the app Is this a git issue? -
Show more button disappears after second press
I simply cannot see the problem here, images are being fetched from a postgres database using ajax and display on the website. We limit the images shown to 5 when the page loads initially but there's a load more button which is supposed to show 5 more images when clicked, which it does but only twice and then it disappears while there are still images to load. Could someone please detect a mistake because I can't seem too find it. Or help rewrite the methods. Thanks in advance. Here's the code: //////////////////////// FETCH SEARCH RESULTS ////////////////////////// const fetch_result = async (data) => { Site.spinner(true) // console.log(data) document.querySelector('html').classList.remove("fixed2") try { const response = await $.ajax({ method: 'GET', url: '/api/v1/creators/search/?' + data, data: {limit:3, offset:0} }) .then(response => response.data) clear_dom() console.log(response) display_results(response.results) Site.spinner(false) let showMore = document.querySelector('#show_more_btn') if (response.next) { showMore.classList.remove('hide') showMore.addEventListener('click', (ev) => { //ev.preventDefault(); showMore.disabled = true show_more_results(response.next) }) } else { showMore.classList.add('hide') } } catch (error) { if (error) { // console.log(error) Site.spinner(false) } } } //////////////////////// SHOW MORE SEARCH RESULTS ////////////////////////// const show_more_results = async (url) => { try { const response = await fetch(url, { method: 'GET' }) Site.spinner(false) if (response.status === 200) { const creators = … -
Remove file objects from children models on delete
My model File has as main purpose to link multiple files for one Invoice. class File(models.Model): invoice = models.ForeignKey(Invoice, related_name = 'files', on_delete = models.CASCADE) file = models.FileField(upload_to = 'storage/invoicing/') def delete(self, *args, **kwargs): self.file.delete() return super(File, self).delete(*args, **kwargs) When i delete one instance of my model File, the file stored in storage/invoicing is also deleted because of my modified delete() method. However, if i delete the instance from the parent model Invoice, the file is not deleted. Even with the File instance being removed from the database, the file is still acessable. How can i code the parent model to delete everything from the children model, including the files? I've searched a bit and i know that probably signals like post_delete can help me here, but i really don't know how to code it. -
Django Rest Framework serializing queryset fetchedn with value_list
I'm trying to query a specific column from my table. I've tried doing it with this team_lenDeserialized = RolesInTeam.objects.values_list('user_id', flat=True).filter(academic_year_id=9).filter(deleted=0) team_lenDict = RolesInTeamSerializer(team_lenDeserialized, many=True) team_len = orderedDictToJSON(team_lenDict.data) After that I run it through a function that converts it to JSON def orderedDictToJSON(orderedDict): return json.loads(json.dumps(orderedDict)) then I go and manipulate it further. However if I try to serialize and convert the team_lenDeserialized I get an error that states AttributeError: Got AttributeError when attempting to get a value for field `user_id` on serializer RolesInTeamSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'user_id'. This is my model for that table class RolesInTeam(models.Model): user_id = models.IntegerField() team_id = models.IntegerField() role_id = models.IntegerField() deleted = models.IntegerField() academic_year_id = models.IntegerField() class Meta: managed = False db_table = 'roles_in_team' and my serializer class RolesInTeamSerializer(serializers.ModelSerializer): class Meta: model = RolesInTeam fields = ['id', 'user_id', 'team_id', 'role_id', 'deleted', 'academic_year_id'] I have no clue what's happening or why it's not working. -
Deleting Migration Files and Getting django.db.migrations.exceptions.NodeNotFoundError:
I have deleted all of migration files and now I am trying to $ python manage.py makemigrations but it is returning django.db.migrations.exceptions.NodeNotFoundError: Migration notifications.0001_initial dependencies reference nonexistent parent node ('blog', '0012_auto_20201118_22 55') How should I fix this error and start migrating from the beginning? The reason for deleting the migration files is due to removing a function that kept returning an error due one of the migration files so I decided to start clean with them. Any ideas on what step I should take to start migrations and migrate again? -
Django PermissionRequiredMixin restricting access to specific users
I hope someone can assist me, i am trying to give custom permissions to a page/view to only 1 user with specific access/permissions. I have a model that looks like this: class Book(models.Model): id = models.UUIDField( primary_key = True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) cover = models.ImageField(upload_to='covers/', blank=True) class Meta: permissions = [ ('special_status', 'Can read all books'), ] def __str__(self): return self.title def get_absolute_url(self): return reverse('books_detail', args=[str(self.id)]) And a view: class BooksDetailView( LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Book context_object_name = 'book' template_name = 'books/books_detail.html' login_url = 'account_login' permission_required = 'books.special_status' I have given the specific user permissions via admin console however any user other than admin is getting 403 Forbidden can anyone tell me how to fix this or what seems to be the problem -
How to get rid of Django security vulnerabilities warning signs in terminal
I have a simple Django project with a PostgreSQL backend and I can't seem to get rid of the Django security vulnerabilities warning signs on my terminal. Settings.py: import os ... ENVIRONMENT = os.environ.get('ENVIRONMENT', default = 'development') ... SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['localhost', '127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... 'HOST': 'db', 'PORT': 5432 } } if ENVIRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_REFERRER_POLICY = 'same-origin' docker-compose.yml: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY="SECRET_KEY" - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:12.3 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: docker-compose-prod.yml: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY="SECRET_KEY" - DEBUG=0 - ENVIRONMENT=production ports: - 8000:8000 depends_on: - db db: image: postgres:12.3 What I am running on the terminal: sudo docker-compose down sudo docker-compose -f docker-compose-prod.yml -f docker-compose.yml up -d --build sudo docker-compose exec web python manage.py check --deploy After running it "sudo docker-compose exec web python manage.py check --deploy", I … -
How can i handle overlaps, reservation and open/close times for a business with django?
Im working on a project that is for making reservations, the business that are registered have open and close times: open_times = [{opens: 09:00am, closes: 13:00}, {opens: 15:00am, closes: 21:00}] --> Naps are really common in Uruguay so everyone closes theirs business after lunch xD an between those times an user can make reservations. Which could be the best approach for this? I can make a new class like class OpenTimesRanges: open_time = models.DateTimeField() close_time = models.DateTimeField() business = models.ForeignKey('Business') and these 3 field are unique together? use pandas for handling overlaps between times and reservations? Any recomendations is appreciated -
Is there a way I can import java output to a form class in a CreatView on django?
I would like to create a view that will autofill the data in my html template from a button click. how can I do this? Is it possible? What kind of documentation is available on the subject? Thank you. I have included the template for the create_entry, Entry model, and CreateEntryView information. <!-- templates/forages/entry_new.html --> {% extends 'base.html' %} {% block content %} <h1>New Entry</h1> </br> <button class="btn btn-primary ml-2" onclick="getLocation()">Location</button> </br> <p id="location"></p> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success ml-2" type="submit">Save</button> <a href="{% url 'project_list' %}" class="btn btn-warning ml-2">Cancel</a> </form> <script> var x = document.getElementById("location"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "</br>Latitude: " + position.coords.latitude + "</br>Longitude: " + position.coords.longitude; } </script> {% endblock content %} models.py class Entry(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE, related_name='entries') foraged_material = models.CharField(max_length=255, choices=FORAGED_MATERIALS ) short_comment = models.TextField(max_length=255, help_text="You may type a 255 char short description of your find or leave the current date and time.", default=datetime.datetime.now()) latitude = models.DecimalField( max_digits=11, decimal_places=8, null=True, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=8, null=True, blank=True) count = models.DecimalField(max_digits=14, decimal_places=3, null=True, blank=True) unit = models.CharField(max_length=56, … -
Problem to save values with signal in django
With this signal, i try to save the values on same table, but it save initial value (total_ht=0, total_tva=0, total_ttc=0) instead of values 10 20 30, and when i update the invoice without any changes, it s updated and it display the correct values. class Invoice(models.Model): date = models.DateField(default=timezone.now) total_ht = models.DecimalField(max_digits=20, decimal_places=2, default=0) total_tva = models.DecimalField(max_digits=20, decimal_places=2, default=0) total_ttc = models.DecimalField(max_digits=20, decimal_places=2, default=0) def calculate(self, save=False): total_ht = 0 total_tva = 0 total_ttc = 0 for invoiceitem in invoiceitems: total_ht += 10 total_tva += 20 total_ttc += total_ht + total_tva totals = { 'total_ht': total_ht, 'total_tva': total_tva, 'total_ttc': total_ttc, } for k,v in totals.items(): setattr(self, k, v) if save == True: self.save() return totals def invoice_pre_save(sender, instance, *args, **kwargs): instance.calculate(save=False) pre_save.connect(invoice_pre_save, sender=Invoice)