Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
window.location.href only gets the host name and not the whole path of the current page
Every time I try to copy link, it only copies the host name and not the full path of the page where I'm at. JS Code: document.getElementById('copyLink').onclick = function() { navigator.clipboard.writeText(window.location.href); } -
Stop updating Django query
query = Movimentacao.objects.all() for m in movimentacoes: # this query couldn't be update everytime an item is added to database q = query.filter(entrada_saida=m[0], data=m[1], movimentacao=m[2], produto=m[3], instituicao=m[4], quantidade=m[5], preco_unitario=m[6], valor_da_operacao=m[7]) # check if the object exist if q.exists(): pass else: # new object is going to be created because it does NOT exist yet line = Movimentacao(entrada_saida=m[0], data=m[1], movimentacao=m[2], produto=m[3], instituicao=m[4], quantidade=m[5], preco_unitario=m[6], valor_da_operacao=m[7]) counter += 1 line.save() How can I prevent this 'q' query from being update everytime the looping is repeated? What I'd like is get the original objects from the database. -
Error message in installing PostgreSQL extensions in Django project
Following a tutorial (which is over a year old), the instructions for creating an empty migration in an app named "accounts", in order to install PostgreSQL extensions, is as follows: python manage.py makemigrations accounts --empty --name="postgres_extensions" But when I enter this line in my Terminal, I get the following error: ModuleNotFoundError: No module named 'settings' Looking at the documentation in djangoproject.com, it seems the correct way to enter this in the Terminal would be this: python manage.py makemigrations --empty accounts --name postgres_extensions But when I enter that in my Terminal, I get the same error as above. -
How to display conditional form field that is dependent on an attribute of a selected foreign key on django model form
I want to conditionally display either frequency_input or duration_input fields based on the behavior.recording attribute of the selected behavior. I have a Trial form that currently displays 3 fields: behavior_name (foreign Key) dropdown frequency_input duration_input Im not sure if i should the best method to solve this (Javascript or solve in the View)? Trial Model class Trial(models.Model): behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE) client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE) frequency_input = models.PositiveIntegerField(default=0, blank=True) duration_input = models.DurationField(blank=True, default=timedelta(minutes=0)) class Meta: verbose_name_plural = 'trials' def __str__(self): return str(self.id) Behavior Model RECORDING_CHOICES = ( ('Rate','RATE'), ('Duration','DURATION'), ('Frequency','FREQUENCY') ) class Behavior(models.Model): name = models.CharField(max_length=200) goal = models.CharField(max_length=200) recording = models.CharField(max_length=10, choices=RECORDING_CHOICES, null=False) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Active') def __str__(self): return self.name Trial Form class TrialForm(forms.ModelForm): class Meta: model = Trial fields = ('behavior_name','frequency_input', 'duration_input') Add Trial View def add_trial(request, clientsession_id): client_session = Client_Session.objects.get(id=clientsession_id) if request.method != 'POST': form = TrialForm() else: form = TrialForm(data=request.POST) if form.is_valid(): add_trial = form.save(commit=False) add_trial.client_session = client_session add_trial.save() return HttpResponse(status=204, headers={'HX-Trigger': 'trialupdated'}) context = {'client_session': client_session, 'form': form} return render(request, 'sessions/add_trial.html', context) -
Avoid hard coding template variables in django context dictionary
From the documentation, the context dictionary needs to have the same variable name as the template variable. Is there a way to avoid duplicating the variable names and hard coding them when creating the context dictionary? Example: Template : <h1>{{ title }}</h1> <h4> {{ date }}</h4> <p> {{ write_up }}</p> The keys in the context dictionary needs to have the same names as the template as follows: { 'title': 'some_value', 'date': 'some_date', 'write_up': 'some_other_value' } Is there a way to prevent hard coding the values in both places, or to share the values via a constants file? So that the template and context dictionary would look something like this. <h1>{{ CONST.title }}</h1> <h4> {{ CONST.date }}</h4> <p> {{ CONST.write_up }}</p> { CONST.title: 'some_value', CONST.date: 'some_date', CONST.write_up: 'some_other_value' } This way, we prevent duplicating the variable names. -
Css intellisense doesn't work after django extension
after i install django extension on VScode css intellisense stop works in .html but in .css it's fine this is .html and css intellisense doesnt' but in the .css all work fine how can i fix this problem? -
request.body not giving the desired json in django
i have started exploring api stuffs in django i want some JsonResponse in Django but i am not getting it views.py from django.shortcuts import render from django.http import JsonResponse import json # Create your views here. def api_home(request, *args, **kwargs): body = request.body print(body) data = {} try: data = json.loads(body) except: pass # print(data) data['headers'] = dict(request.headers) data['content_type'] = request.content_type return JsonResponse(data) Output in terminal b'' expected OUTPUT b'{"query":"Hello World!"}' Python file import requests endpoint = "http://127.0.0.1:8000/api" get_response = requests.get(endpoint, json={"query":"Hello World!"}) print(get_response.json()) Output of this file {'headers': {'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'content_type': 'text/plain'} Expected OUTPUT {'query':'Hello World!','headers': {'Content-Length': '', 'Content-Type': 'text/plain', 'Host':'127.0.0.1:8000', 'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip,deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'content_type': 'text/plain'} I am not getting that why i am getting different output here -
Group queryset by field
I am working with Django and Django REST framework. I have a model called Selection that contains field called category, when i query the model to send the result to the frontend i get it with the following structure: [ { "id": 1, "category": "SHOES", "products": 122, "created_at": "2021-09-11", }, { "id": 2, "category": "SHOES", "products": 4, "created_at": "2021-10-07", }, { "id": 3, "category": "CLOTHES", "products": 0, "created_at": "2021-10-08", }, ] I need to put the selections of the same category in an array and remove the grouped-by category, like this: { "SHOES": [ { "id": 1, "products": 122, "created_at": "2021-09-11", }, { "id": 2, "products": 4, "created_at": "2021-10-07", } ], "CLOTHES": [ { "id": 3, "category": "CLOTHES", "products": 0, "created_at": "2021-10-08", } ] } I considered to making it with Javascript in the frontend, but before i wanted to know if there's a way to do this from Django. -
Error: 'User' object has no attribute 'exists' on Heroku url, but works on local host url
So I am trying to request the logged in user, from the Heroku url, but gives me the error 'User' object has no attribute 'exists'. Whenever I try to do the exact same task, but on my local host url, I get the user and everything works perfectly. I think the issue roots from my database being out of synce, but I ran python3 manage.py makemigrations and migrate, but that didn't change anything. Also on a related note, when I try to sign into the admin with my super user, it works on the local host but not on Heroku. I know it's because it also doesn't think the superuser exist. I was going to change my Database, to mysqlite to postgresql, with the hopes of that fixing it, because that was already on the todo list for my full stack, but I want to figure out why this is happening before moving forward. If anyone could help that would be fantastic. -
nginx cannot find files in /home/ubuntu/
I don't understand why nginx cannot find files when the root is under home directory, e.g. /home/ubuntu/tabs. It will give 404 error. It works fine when the root is /var/www/tabs. server{ listen 80; #root /var/www/tabs; root /home/ubuntu/tabs; server_name 18.191.229.199; index main.html ; location / { try_files $uri $uri/ =404; } location /folder { try_files /folder/main1.html /folder/main2.html =404; } } -
how to save foreign key from django html template
I want to save data from html template select field in django. html example code: <label for="type" style="color:red;">Short Name *</label> <input type="text" name="short_name" class="form-control" required placeholder=""> <br> <br> <select style='bakground-color:red' name="category" required class="form-control show-tick"> <option value="" selected="selected">---------</option> {% for cat in category %} <option value="{{ cat }}">{{ cat }}</option> {% endfor %} </select> Django code: Views.py def addBooks(request): template = 'admin_panel/add_books.html' category = Category.objects.all() book_details = BookDetails.objects.all() context = { "page_title": "Add Book", "category": category, "book_details" :book_details, } if request.method == "POST": short_name = request.POST.get('short_name', None) category = request.POST.get('category',None) book_details = BookDetails.objects.create(short_name=short_name, category=category) return render(request, template,context) models.py class BookDetails(models.Model): id = models.AutoField(primary_key=True) short_name = models.CharField(max_length=50, unique=True, db_index=True) category = models.ForeignKey( Category, on_delete=models.CASCADE ) Error Showing: ValueError at /superadmin/add_books/ Cannot assign "'Story'": "BookDetails.category" must be a "Category" instance. How to solve this problem? -
Accessing dataclass properties by name in Django template
In Django, I have created a dataclass to help me move data around in a standardized way: # models.py class Person(models.Model): name = CharField(max_length=50) #utils.py @dataclass class Performance: person: Person last_year: int five_years: int The idea here is that I can access the properties by name when transferring them to the template: #views.py class IndexView(View): def get(self, request): persons = Person.objects.filter(name="pam") perfs_array = [] for person in persons: p = Performance() p.last_year = #some math p.five_years = #more math perfs_array.append(p) context = {"perfs": perfs_array} return render(...) The goal is to be able to do this: <!--index.html--> {% for perf in perfs %} <h1>{{ perf.person.name }}</h1> <p>last year's performance: {{ p.last_year }}</p> {% endfor %} However, I can only access the data using numbered indices: <!--index.html--> {% for perf in perfs %} <h1>{{ perf.0.name }}</h1> <p>last year's performance: {{ p.1 }}</p> {% endfor %} This made it very hard to write correct code and to debug the templates when things go inevitably south. Is there a way to access the data with named indices? Thanks! -
serializer showing name of model
I want to serialize data from nested queryset: I have working code but output from serializer showing too many data. I want hide this for security reason. example output: (...) "gallery": "[{"model": "mainapp.imagesforgallery", "pk": 1, "fields": {"user": 1, "image": "uploads/2022/8/6/drw/Adapta-KDE-theme_JOgL4kO.webp", "thumbnail": ""}}]" (...) this is models.py class ImagesForGallery(models.Model): user = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return 'User: {} || Image: {}'.format(self.user, self.image) class Gallery(models.Model): project = models.ForeignKey(Projects, null=True, blank=True, on_delete=models.CASCADE) project_gallery = models.ManyToManyField(ImagesForGallery, blank=True, related_name='project_gallery') def __str__(self): return '{}'.format(self.project) This is my view class HomeView(viewsets.ModelViewSet): serializer_class = ProjSerializer queryset = Proj.objects.all() def list(self, request, *args, **kwargs): response = super(HomeView, self).list(request, args, kwargs) gal = Gallery.objects.all() for d in response.data: for g in gal: if d['uuid'] == str(g.project.uuid): qs = g.project_gallery.get_queryset() serialized_obj = serializers.serialize('json', qs) d['gallery'] = serialized_obj return response This code compares the project model to the photo gallery model. If uuid is correct, include this gallery in the project and send json. I'm not sure the code is efficient and safe. The question is how to modify the code so that it does not show the model name. -
Using Below Code i m able to find states present in a country, is There any method to find cities within the given states using python
Using this code i am able to find states of country i want to find all cities within given state, suppose i enter the state name i get all cities within that state from countryinfo import CountryInfo name = "India" country = CountryInfo(name) data = country.info() print(data["provinces"]) -
Why I am getting access denied when enabling the service of the systemctl?
I am configuring a Nginx server in Django. I am in the stage of enabling the /etc/systemd/system/emperor.uwsgi.service but I am getting Failed to enable unit: Access denied error when I am running the command systemctl enable emperor.uwsgi.service. Here emperor.uwsgi.service file's content: [Unit] Description=uwsgi emperor for projet agricole website After=network.target [Service] User=username Restart=always ExecStart=/project_path/my_venv/bin/uwsgi --emperor /project_path/my_venv/vassals --uid www-data --gid www-data [Install] WantedBy=multi-user.target what can I do in order to solve this issue? Please assist. -
TypeError: fromisoformat: argument must be str
[akbar@fedora src]$ ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, core, product, sessions, users Running migrations: Applying blog.0007_blog_created_at...Traceback (most recent call last): File "/home/akbar/Desktop/Tech/E-commerce-Unistore-Wolves/src/./manage.py", line 22, in main() File "/home/akbar/Desktop/Tech/E-commerce-Unistore-Wolves/src/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/migration.py", line 131, in apply operation.database_forwards( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/operations/fields.py", line 108, in database_forwards schema_editor.add_field( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 599, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 345, in column_sql " ".join( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 296, in _iter_column_sql default_value = self.effective_default(field) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 410, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 910, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 1408, in get_db_prep_value value = self.get_prep_value(value) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 1403, in get_prep_value return self.to_python(value) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line … -
Display of parent categories does not work
Greetings! I can't solve this problem myself, I have the following code: urls.py re_path(r'^category/(?P<hierarchy>.*)$', show_category, name='category'), I tried different things, settled on two options after the comment "# No category, show top-level content somehow" views.py def show_category(request, hierarchy=None): hierarchy = (hierarchy or "").strip("/") # Remove stray slashes if hierarchy: category_slug = hierarchy.split('/') parent = None for slug in category_slug[:-1]: parent = Categories.objects.get(parent=parent, slug=slug) category = Categories.objects.get(parent=parent, slug=category_slug[-1]) else: category = None if category: return render(request, 'shop/categories.g.html', {'instance': category}) # No category, show top-level content somehow # categories = Categories.objects.all() category = Categories.objects.filter(parent=None) return render(request, 'shop/categories.g.html', {'instance': category}) The problem is that the path /category/window-and-door opens the required category. But with /category/ nothing is displayed, the template uses {{ instance.title }} -
Django: Problem deleting an Authenticated User profile
I'm having problems deleting a user, where the authenticated user can delete their own account. But what happens is that the page just refreshes, in the same template and returning '200 ok from POST' [06/Aug/2022 11:46:33] "POST /members/profile/ HTTP/1.1" 200 4998 members.views.profiles.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User @login_required(login_url="/accounts/login/") def profile(request): template_name = "members/profile.html" context = {} return render(request, template_name, context) def profile_delete(request, pk): user_profile = User.objects.filter(pk=pk) template_name = "members/profile_delete.html" context = { "user_profile": user_profile, }, if request.method == "POST": user_profile.delete() return render(request, template_name, context) return render(request, template_name, context) members.urls.py from django.urls import path from allauth.account import views as allauth_views from . import views app_name = "members" urlpatterns = [ path("login/", allauth_views.LoginView.as_view(), name="login"), path("logout/", allauth_views.LogoutView.as_view(), name="logout"), path("profile/", views.profile, name="profile"), path("profile/<int:pk>/delete/", views.profile_delete, name="profile_delete"), ] profile.html <div> <form method="POST"> {% csrf_token %} <p>Are you sure you want to delete <strong>{{ user | title }}</strong> ?</p> <button class="btn btn-danger" href="{% url 'members:profile_delete' user.pk %}" type="submit"> Delete </button> </form> </div> -
Django getting error exceptions must derive from BaseException
Info: I want to upload files using Uppy in frontend and django-tus as backend for file processing. I am getting error TypeError: exceptions must derive from BaseException. Traceback Internal Server Error: /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b9 Traceback (most recent call last): File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/django_tus/views.py", line 37, in dispatch return super(TusUpload, self).dispatch(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/django_tus/views.py", line 82, in head tus_file = TusFile.get_tusfile_or_404(str(resource_id)) File "/home/c0d3/git/django-rus-multi-files/django_tus/tusfile.py", line 75, in get_tusfile_or_404 raise TusResponse(status=404) TypeError: exceptions must derive from BaseException [06/Aug/2022 14:36:42] "HEAD /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b9 HTTP/1.1" 500 103054 [06/Aug/2022 14:36:42,624] - Broken pipe from ('127.0.0.1', 35814) [06/Aug/2022 14:36:42] "POST /tus/upload/ HTTP/1.1" 201 0 [06/Aug/2022 14:36:42] "PATCH /tus/upload/8295bef4-c94a-4ab7-9c75-2635c74428d8 HTTP/1.1" 204 0 https://github.com/alican/django-tus/blob/master/django_tus/tusfile.py class TusUpload(View): def head(self, request, resource_id): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) return TusResponse( status=200, extra_headers={ 'Upload-Offset': tus_file.offset, 'Upload-Length': tus_file.file_size, }) def create_initial_file(metadata, file_size: int): resource_id = str(uuid.uuid4()) cache.add("tus-uploads/{}/filename".format(resource_id), "{}".format(metadata.get("filename")), settings.TUS_TIMEOUT) cache.add("tus-uploads/{}/file_size".format(resource_id), file_size, settings.TUS_TIMEOUT) cache.add("tus-uploads/{}/offset".format(resource_id), … -
In a registration form there are 5 different phone numbers for one user i need to store all 5 numbers in different table(In django). How to solve this
in models.py class UserForm(models.Model): name = models.CharField('Name',max_length=20) email = models.EmailField(max_length=20) city = models.CharField(max_length=20) class Meta: db_table = 'userform' def __str__(self): return self.name class PhoneNumber(models.Model): user = models.ForeignKey(UserForm, on_delete=models.CASCADE) # phone = models.CharField(user, max_length=10) phone1 = models.CharField(user, 'Phone',max_length=10, blank=True) phone2 = models.CharField(user, max_length=10, blank=True) phone3 = models.CharField(user, max_length=10, blank=True) phone4 = models.CharField(user, max_length=10, blank=True) phone5 = models.CharField(user, max_length=10, blank=True) class Meta: db_table = 'phonenumber' I tried applying this method, i have a confusion that how to manage view.py and html form file -
Django creating multiple groups with post_save
I need to auto-create several groups with a post_save signal. I almost have this working however, as a novice, I can't get the syntax right. When I use the code below, instead of two groups, I get one group with the name ('manager', 'employee'). How would I change this to add two groups - manager and employee? # autocreate basic employee groups when new company is created @receiver(post_save, sender=Tenant) def create_basic_group(sender, created, **kwargs): if created: # Get or create group new_group, created = Group.objects.get_or_create( name=('manager', 'employee')) -
Django, how to save a randomly generated variable for the next session after POST method
I have an integer in Views.py which is generated randomly. I send it to Index.html: return render(request, 'index.html', {'number':number}) Then I have a simple form in forms.py class AForm(forms.Form): information = forms.CharField(label='Your answer', max_length=100) And this form in Index.html with POST method: <form action="{% url 'index' %}" method = POST> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> which leads to the same page and function. And I want to return via this POST method that number which I previously sent, because now it is already another, taken randomly, because it is the same function. But I already need the previous one. In other words I generate a random number and I need to save it for the next loading, after POST Method. I would even not send that number anywhere if it is possible. Is there a simple, elegant way to do it? I've read about sessions in Django, probably it is the way, but is there an easier way? Thanks. -
The concatenation returns me the name of the variable
I want to create an alert to delete users with sweetAlert, but in the script tag when I create my url from a variable passed as a parameter in the function, the result is only the name of the variable to display and not its value function delInscPart(id){ var url = "{% url 'suppPartners' " +id+" %}" Swal.fire({ "title":"Etes vous sure de vouloir supprimé l invité ?", "text":"Si vous confirmer cette opération, Vous supprimerais cette invité !", "icon":"", "showCancelButton":true, "cancelButtonText":"Anuller", "confirmButtonText":"Je confirme", "reverseButtons":true, }).then(function(result){ if(result.isConfirmed){ window.location.href = url console.log(url) } }) } <td><a href= "#" onClick="delInscPart('{{list.user_inscrit.username}}');"><i data-feather="trash-2"></i>Supprimer</a></td> the result is {% url 'suppPartners' +id+ %} instead {% url 'suppPartners' admin %} -
PyCharm: Cannot connect to postgres-db in docker container
as the title says, I'm having trouble to connect a rather simple database-configuration with my IDE PyCharm. docker-compose.yml db: restart: always image: postgres container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - "5432:5432" networks: - db-net Using it with django, here are my database-settings from the backend, which are working perfectly fine: settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": 5432, } } But when trying to connect the database inside PyCharm with the following settings, I'm getting this error: Note: The field for password was of course filled -> get's cleared everytime someone hits Apply or tries to test the connection. Does anyone might know what I'm doing wrong or maybe had the same problem? Thanks for your help and have a great weekend! -
How Can I Check if Date is Passed from Django Model
I am really new in Django and I want to check if Date Stored in Model is passed. In fact, I am currently working on a ticketing app where users would have to purchase and activate ticket and I want to check if the Event Ticket Date is passed upon activation. My Models: class Event(models.Model): event_name = models.CharField(max_length=100) date = models.DateField(auto_now_add=False, auto_now=False, null=False) event_venue = models.CharField(max_length=200) event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.event_name}" #Prepare the url path for the Model def get_absolute_url(self): return reverse("event_detail", args=[str(self.id)]) class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) My Views for …