Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django: model <name> not recognized in views.py
Background: I want to open the CourseForm in order to edit existing course data by clicking on a link. Problem description: Running the development server, if I click on the link, I get the following error: File "/home/usr/project/workbench/courses/views.py", line 92, in ManageCourseView course = Course.objects.filter(id=id) UnboundLocalError: local variable 'Course' referenced before assignment Line 92 in ManageCourseView: from django.views import generic from .models import Course from .forms import CourseForm from django.shortcuts import render, redirect from django.http import HttpResponseRedirect def ManageCourseView(request, id): course = Course.objects.get(id=id) if request.method == 'POST': form = CourseForm(request.POST, instance=course) if form.is_valid(): # I do something with it else: form = CourseForm(instance=course) return render(request, 'courses/manage_course.html', {'form': form}) Definition of the Course model: class Course(models.Model): name = models.CharField('Kurs', max_length=200) capacity = models.PositiveSmallIntegerField('Anzahl Plätze') start_date = models.DateField('Erster Kurstag') end_date = models.DateField('Letzer Kurstag') price = models.FloatField('Preis', null=True, blank=True) def __str__(self): return self.name I am referencing the Course model in other view functions and there it works perfectly fine. Definition of the CourseForm: class CourseForm(forms.ModelForm): class Meta: model = Course exclude = ['name', 'price'] Extract of the html with the respective link: <div class="column is-two-thirds"> <a href="{% url 'courses:manage_course' course.id %}"> <div class="box has-background-info is-clickable"> <p class="title has-text-white">{{ course.name }}</p> <p class="has-text-white">{{ course.start_date … -
Daphne ModuleNotFoundError: No module named
I'm unable to get the Daphne server running. It always fails with the following error: ModuleNotFoundError: No module named 'apps' /home/prassel/sml-266/simlai-api/apps/asgi.py django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) And I invoke Daphne as follows: daphne -b 0.0.0.0 -p 8000 apps.asgi:application -
How to move Virtualenvwrapper.sh to it's appropriate location?
I am working a new project where it requires me to create a virtual environment since im working with Django frameworks. I been having trouble working creating "mkvirtualenv" and its been kicking my butt for the past couple days. I think I found the underlying problem that Virtualwrapper.sh is not in the right location. I been trying to figure out how to move it into the right location does anybody have some guidance on what to do. /Users/name/opt/anaconda3/bin ----> currently where the file is at the moment I been trying to add it to the .bashrc folder but im having a hard time adding it there. How can I do this so I can successfully run "mkvirtualenv" **I been trying for hours to write .bashrc and research anything but nothing is helping so far -
admin panel in Django creating for to change Product media and text from webpage
I have created a website in Django that contains product details and captions. Now, I want to create a dynamic admin panel that performs the following tasks without using code (because the client has no idea about coding): Add or change product photos and details. change or add any paragraphs or details on the website. ( just like we are changing the our images on social media account without using any coding like using prebuilded system) So here is what to do as the next step in processing this: pls guide me i have tried models but i don't understand it very well -
127.0.0.1:8000 refused to connect after django manage.py runserver
I'm new to python and django. I did the python manage.py runserver in cmd for the first time and it showed starting development server at http://127.0.0.1:8000/. It said: System check identified no issues (o silenced)April 04,2023- 19:42:34 Django version 2.2.4,using settings 'MyProject.settings!Starting development server at http://127.0.0.1:8000/Quit http://127.0.0.1:8000/Quit the server withCTRL-BREAK But in chrome it said "this site cant be reached". It said: ERR SSL PROTOCOL ERROR my setting.py: ALLOWED_HOSTS = ['*',] Can someone help me out with this? -
New wagtail project: main page not working
The problem is the following. I have created a new wagtail project. Nothing special. No changes, just created. At startup I get this. What is this url? Nothing has changed in the project yet, the project is clean... The main page is not displayed, everything is redirected to /catalog. -
Problem with the construct of LoginView.as_view formul
I know that command django.contrib.auth.views import login has changed. That's why I used a new formula. I don't know why my webiste is not working althouh I think that I used a new formula correctly. Everything is fine: the paths to the files are used correctly although my website is not rendered. I will be grateful for any help :) Nornik/urls.py: from django.urls import re_path from django.urls import path from . import views from django.contrib.auth.views import LoginView urlpatterns = [ path(r'^$', views.home), path('login/', LoginView.as_view (template_name='Nornik/login.html'), name='login'), views.py: from django.shortcuts import render, HttpResponse def home(request): numbers = [1,2,3,4,5] name = 'John Lock' args = {'MyName': name, 'Numbers': numbers} return render(request, 'Nornik/home.html',args) tutorial/urls.py: from django.urls import re_path, include from django.urls import path from django.contrib import admin urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^Nornik/', include('Nornik.urls')), I will be grateful for any help :) -
How to stop url redirection to urls ending with '/' in Django?
On my website, few urls are not crawlable and are returning non 200 response code. It is happening because those are getting redirected. Example: https://mywebsite.com/fr -> https://mywebsite.com/fr/ When I crawl https://mywebsite.com/fr/, it returns me 200 but not for https://mywebsite.com/fr. Website is built using django. I am not sure how can I make https://mywebsite.com/fr to return 200 code. Please advise. -
migrating mysql db to django, unique constraints?
Currently I have part of a model: class Flight(models.Model): flight_number = models.PositiveIntegerField(primary_key=True) airline_name = models.ForeignKey(Airline, models.DO_NOTHING, db_column='airline_name') departure_datetime = models.DateTimeField() departure_airport = models.ForeignKey(Airport, models.DO_NOTHING, db_column='departure_airport', blank=True, null=True, related_name='departure_airport') arrival_airport = models.ForeignKey(Airport, models.DO_NOTHING, db_column='arrival_airport', blank=True, null=True, related_name='arrival_airport') arrival_datetime = models.DateTimeField(blank=True, null=True) airplane = models.ForeignKey(Airplane, models.DO_NOTHING, blank=True, null=True) base_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) flight_status = models.CharField(max_length=9) class Meta: managed = False db_table = 'flight' constraints = [ models.UniqueConstraint(fields=['flight_number', 'airline_name', 'departure_datetime'], name='unique_flight') ] class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customer, models.DO_NOTHING) flight_number = models.ForeignKey(Flight, models.DO_NOTHING, db_column='flight_number', to_field='flight_number', related_name='ticket_flight_number') airline_name = models.ForeignKey(Flight, models.DO_NOTHING, db_column='airline_name', to_field='airline_name', related_name='ticket_airline_name') departure_datetime = models.ForeignKey(Flight, models.DO_NOTHING, db_column='departure_datetime', to_field='departure_datetime', related_name='ticket_departure_datetime') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.CharField(max_length=100) date_of_birth = models.DateField() class Meta: managed = False db_table = 'ticket' constraints = [ models.UniqueConstraint(fields=['flight_number', 'airline_name', 'departure_datetime', 'first_name', 'last_name', 'email', 'date_of_birth'], name='unique_ticket') ] But I keep getting the error log while trying to run migrate: ERRORS: atrsapp.Ticket.airline_name: (fields.E311) 'Flight.airline_name' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. atrsapp.Ticket.departure_datetime: (fields.E311) 'Flight.departure_datetime' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint … -
Messages not rendering in djangos built in Login and Logout View
I am trying to show alerts on my home page when some one successfully logs in or logs out, and also show an error alert if something goes wrong with login. All my message alerts are working with all of my views apart from the login and logout views and I have no idea why. VIEWS: def user_login(request): data = cartData(request) cartItems = data['cartItems'] context = { 'cartItems': cartItems, } if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {'context': context}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML: {% if messages %} <div class="alert alert-success" id="msg" role="alert"> <h4 class="alert-heading">Success</h4> {% for message in messages %} <p>{{message}}</p> {% endfor %} </div> {% endif %} -
Authorization is not working for jwt token using axios
settings.py from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-siq5r5k3*sg#858b4w8$i*6c-ubf*zkpjj1wb&chn4v$%t!ve+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dlt.urls' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True } CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dlt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Pytest and pytest-django ends up with assert error
I've been dealing with this for the last 30 mins and I just want to move on from it. Basically, the test returns Assertion Error: E AssertionError: assert {} == {'rant': 'Kulugo', 'slug': 'apostrophe'} E Right contains 2 more items: E {'rant': 'Kulugo', 'slug': 'apostrophe'} E Full diff: E - {'rant': 'Kulugo', 'slug': 'apostrophe'} E + {} tests/rants/test_serializers.py:26: AssertionError Now tracing back the error in line 26: assert serializer.data == invalid_serializer_data I expect everything to pass since this written code is based on a tutorial from testdriven.io Here's the full code: from main.serializers import RantSerializer, CategorySerializer def test_valid_rant_serializer(): valid_serializer_data = { 'id': 1, 'title': "First Rant", 'slug': "first-rant", } serializer = RantSerializer(data=valid_serializer_data) assert serializer.is_valid() assert serializer.validated_data == valid_serializer_data assert serializer.data == valid_serializer_data assert serializer.errors == {} def test_invalid_rant_serializer(): invalid_serializer_data = { 'rant': 'Kulugo', 'slug': 'apostrophe' } serializer = RantSerializer(data=invalid_serializer_data) assert not serializer.is_valid() assert serializer.validated_data == {} assert serializer.data == invalid_serializer_data assert serializer.errors == {"id": ["This field is required"]} -
How to properly upload a CSV file to Django model
I am trying to upload a CSV file to a Django model. Here is the code i have been trying for it to work: def post(self, request): if(request.method=='POST'): # csv_file=request.FILES.get('file') csv_file = request.FILES['file'] with open(csv_file, 'r') as csvfile: # reader=csv_file.read().decode("utf-8") # reader=TimeSeries.import_data(data = open(csv_file)) # reader = csv.reader(csv_file.read().decode('utf-8').splitlines()) reader = csv.reader(csvfile) print("here3") print (reader); for row in reader: print("here4") print(row) queryset = Station.objects.all() print("here5") # serializer_class = TimeSeriesSerializer queryset = queryset.filter(name=row['Station Name']) TimeSeriesInstance=TimeSeries(station=queryset.number,date=row['Date'],hour=row['Time'],value=row['Value']) TimeSeriesInstance.save() # process_file.delay(csv_file) return HttpResponse('Success') The problem is that i have tried to remove and add the above commented lines for somehow check if the code works.But it is throwing different types of errors for different lines. currently it is throwing the error: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Kindly tell what might be the issue? Thanks. -
Extending Django's nav-sidebar with additional options
I am working with Django and currently trying to add options to default nav-sidebar which will not be anyhow connected with models, but will open other additional pages. The best idea i got is to extend the default base_site.html with my new option for a sidebar. Therefore i resulted in the following code: {% extends "admin/base_site.html" %} {% block sidebar %} <div class="app-dashboard module current-app"> <h2>Custom Options</h2> <ul> {% include "admin/custom_sidebar.html" %} </ul> </div> {{ block.super }} {% endblock %} custom_sidebar.html: <th class="model-group"><a href="{% url 'email' %}">Send message</a></th> This indeed extends the page, but adds my option to the bottom of the content block, whereas I want it to appear in my sidebar. Here is how it looks: I understand I practically didnot affected the default nav_sidebar anyhow, but I am out of ideas how to make it. Is there a way i can modify a nav_sidebar in django? And if so how shall i do it? -
Django - How to show Full name of the Month in Admin Panel
I want to show Full month (like April or September) in Django Admin Panel. But it keeps show me first 3 letter of the month or a number. Is there any way to do make it show full month on Admin Panel? Thanks! -
Celery task stays running forever, but completes successfully
My Task: @app.task(ignore_result=True) def leaks_scan(target: str, remove_type: str = "old", **kwargs): url = settings.API_URL + "leaks" skip = 0 limit = 1000 max_limit = 5000 if remove_type == "all": remove_all_data(Leak, target) scan_id = None target_id = None while True: data = get_data(url, target, skip=skip, limit=limit) count = data.get("count") data = data.get("data", []) if not data: if not count: remove_all_data(Leak, target) break break scan_id, target_id = load_leak_data(data) skip += limit if skip > max_limit: break if remove_type == "old" and scan_id and target_id: remove_old_data(Leak, scan_id, target_id) print("Leak scan completed") Notice that this task has a print statement that prints Leak scan completed in the last line Logs: Task received: Task finished (debug print line): The task works as expected and completes successfully. However, when I check the Celery worker logs, the task stays in the running state indefinitely, even though it has been completed: Can anyone suggest a solution or provide any guidance on how to troubleshoot this issue? Thanks in advance for your help. Environment & Settings Celery version: celery report Output: software -> celery:5.2.7 (dawn-chorus) kombu:5.2.4 py:3.11.2 billiard:3.6.4.0 py-amqp:5.1.1 platform -> system:Linux arch:64bit, ELF kernel version:5.15.90.1-microsoft-standard-WSL2 imp:CPython loader -> celery.loaders.default.Loader settings -> transport:amqp results:disabled deprecated_settings: None Broker & Result … -
Django: Starting a celery worker when a button is clicked
I have a button which puts a PCAP file into a parsing function. When my button is clicked "Upload File" it calls my form_upload view and I want my celery task to start running so it displays a progress bar while the file is being parsed. However, when clicking "Upload File", the page loads and then the celery starts. So the progress bar does not display until after the page loads and the function finishes parsing. Here is my index.html <form action="{% url 'upload' %}" class="row gy-1 gx-2 align-items-center" id='startIDS' method="post" enctype="multipart/form-data" style="margin-bottom: 10px;"> <div class='col-auto'> <input class="form-control" type="file" name="file"> </div> <div class='col-auto'> {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm" style="float: right;" onclick="wait()">Upload File</button> <script> function wait() { //go_to_sleep.delay(5); alert("Click Ok and then please wait for upload to finish"); } </script> </div> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <div id="celery-result"></div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <!--CELERY--> {% if task_id %} <!-- avoid any errors by just checking if the task_id exists --> <script> // JQuery document.addEventListener("DOMContentLoaded", function() { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> {% endif %} </form> Here is my views.py `# Render … -
Django returns a tuple instead of returning data
I have a simple model that is supposed to store some basic nutritional information about food, but whenever I create or edit the model it returns a tuple instead of the data. The app is simple and these are the only models I have in them. Here is the model: class User(AbstractUser): test_field = models.CharField(max_length=100) def __str__(self): return self.username class Food(models.Model): name = models.CharField(max_length=100, null=False, blank=False), calories = models.IntegerField(default=0, null=False), protein = models.IntegerField(default=0), fat = models.IntegerField(default=0), rel_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) At first I thought it was an issue with how I was saving the model, so I tried creating one through the shell with the following commands: from api.models import User, Food f = Food() f.name = "Test" f.calories = 1 f.rel_user = User.objects.get(id=1) f.save() If I call f.rel_user, it returns myemail@gmail.com, but if I call f.name, it returns (<django.db.models.fields.CharField>,). In order to try to fix this, I've looked through the getting started project on https://docs.djangoproject.com/en/4.2/intro/tutorial01/, and have made sure that my settings.py, and my models are written like the ones on the site. I've tried using both the shell and a form to create test Food objects. How can I fix this so when I try to get … -
HDF5-DIAG: Error detected in HDF5 on django project
Im working on my django project and when I made a copy of the project on a new pc I got this error (repeated multiple times) each time I load the server: HDF5-DIAG: Error detected in HDF5 (1.10.7) thread 1: #000: H5T.c line 1915 in H5Tcopy(): not a datatype or dataset major: Invalid arguments to routine minor: Inappropriate type and when I stop the server I get another one HDF5: infinite loop closing library L,T_top,P,P,FD,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E I have no idea where this come from, any light to where to find the issue?, deprecated model datatypes? postgres/postgis problem? thanks -
Django: How to loop through query set and change the boolean field to True in django?
I am trying to loop through a queryset in django and turn all the boolean fields in the queryset to true. I want to turn this booleans to True on the success_page, so i tried doing it like this @login_required def PaymentSuccessView(request): ... order = get_object_or_404(CartOrder, stripe_payment_intent=session.id) cart_order_items = CartOrderItem.objects.filter(order=order) for c in cart_order_items: c.paid = True c.save() return render(request, "payment/payment_success.html", {"order": order}) The problem is that, this still does not work even after i get redirected to the success page on successful transaction. I also tried doing this in the model, i am not sure if it's the right way to do this, but i tried it and it still did not work class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) paid = models.BooleanField(default=False) .... def save(self, *args, **kwargs): if self.order.payment_status == "paid": self.paid = True return super(CartOrderItem, self).save(*args, **kwargs) These are my model fields class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) paid = models.BooleanField(default=False) ... class CartOrder(models.Model): vendor = models.ManyToManyField(Vendor) buyer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="buyer") stripe_payment_intent = models.CharField(max_length=200,null=True, blank=True) -
When should I use to_representation?
I'm looking for guidance on if my usage of to_representation is a decent approach or if there is a better way to solve my specific problem. I have this code in my serializers.py: from rest_framework import serializers from .models import Project, Task, TaskStatus class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ["name", "description", "start_date", "end_date", "pkid"] def create(self, validated_data): organization = validated_data.pop('organization', None) project = Project.objects.create(**validated_data) if organization: project.organization = organization project.save() return project class TaskStatusSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ["name", "description", "pkid"] def create(self, validated_data): task_status = TaskStatus.objects.create(**validated_data) return task_status class TaskSerializer(serializers.ModelSerializer): project = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all()) status = serializers.PrimaryKeyRelatedField(queryset=TaskStatus.objects.all()) class Meta: model = Task fields = ["name", "description", "project","status","pkid"] def create(self, validated_data): project = validated_data.pop('project') status = validated_data.pop('status') task = Task.objects.create(project=project, status=status, **validated_data) task.save() return task def to_representation(self, instance): representation = super().to_representation(instance) representation['project'] = ProjectSerializer(instance.project).data representation['status'] = TaskStatusSerializer(instance.status).data return representation What I'm trying to do is have my TaskSerializer respond to an API request and provide me task, taskstatus, and project objects that I use to populate a Vue list. Within the view list, I have a create modal that loads where the user can select the project via drop down and specify the status. These … -
django-storages FTP doesn't work on production
I've frontend (made with Angular) on a cloud hosting and backend (made with DRF) on pythoneverywhere. I configured django-storages so that it sends the files that the user uploads to the server where the frontend is located via FTP. While I use it in development, on localhost, it works perfectly, however when I use it in production I get a Server Error (500). This is the error that shows the console: 2023-04-04 19:32:00,158: Internal Server Error: /admin/portfolio/developer/add/ Traceback (most recent call last): File "/home/ferreromanuel/.virtualenvs/portfolio-virtualenv/lib/python3.10/site-packages/storages/backends/ftp.py", line 91, in _start_connection ftp.connect(self._config['host'], self._config['port']) File "/usr/local/lib/python3.10/ftplib.py", line 158, in connect self.sock = socket.create_connection((self.host, self.port), self.timeout, File "/usr/local/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/local/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused **NO MATCH** During handling of the above exception, another exception occurred: **NO MATCH** Traceback (most recent call last): ... raise FTPStorageException( storages.backends.ftp.FTPStorageException: Connection or login error using data {'active': False, 'path': '/htdocs/assets/media/', 'host': 'ftp.manuelferrero.com.ar', 'user': 'webmaster.manuelferrero.com.ar', 'passwd': '*********', 'port': 21} and this is my settings.py: import os import environ from pathlib import Path env = environ.Env() environ.Env.read_env() SITE_NAME = 'Manuel Ferrero' BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = os.environ.get("DEBUG") == "True" ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", … -
How to create a constraint on a field and the date value of created_at in django?
I want to create a constraint that allows an instance of a value for a field to exist only once per day. Meaning if I have a column custom_id and a created_at field, an example value '1' of custom_id can only exist once on 2023-01-01, so adding another field will fail. I am using postgres as a database and from what I have gathered, a query similar to EXCLUDE USING gist (custom_id WITH =, date_trunc('day', created_at) WITH =) However I am failing to replicate this in a django model according to the available -
imported a populated table on to postgresql but I need the model in Django . What to do?
I have a set of populated tables (country,region town etc) that I have imported onto Pgadmin (postgresql) but I need the models in Django now so that I can work on those tables. However, like I said, these were tables with data, so if I write the model definition in Django, it will either destroy my tables by overwriting them (leaving them empty) or it will give an error. I prefer to work now with models, but can't create them because the tables already exist. What can I do? I know you could say, well, you should have first defined the models. Well, no, because the three tables are linked by multiple composite primary keys and actually I got the code for the model once the tables have been imported to the pgadmin, and the model definition was quite complex. If you are curious to see how a model definition looks here it goes: ` class Localidades(models.Model): id_localidad = models.AutoField(primary_key=True) id_region = models.SmallIntegerField() id_pais = models.SmallIntegerField() id_idioma = models.SmallIntegerField() nombre_localidad = models.CharField(max_length=150) x = models.FloatField() y = models.FloatField() exacto = models.SmallIntegerField() class Meta: managed = False db_table = 'localidades' unique_together = (('id_localidad', 'id_region', 'id_pais', 'id_idioma'),) ` I did not even … -
Django primary key field not showing up in postgres database
I have a model class import uuid import datetime, pytz from django.db import models from django.conf import settings class Topic(models.Model): key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=168) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField() updated = models.DateTimeField(default=datetime.datetime(2000, 1, 1, 0, 0, 0, 0, pytz.UTC)) keyword_json = models.TextField() model_bin = models.BinaryField() article_ttl = models.FloatField(default=48.0) timeliness = models.FloatField(defautl=4.0) It results in a migrations file containing the block name='Topic', fields=[ ('key', models.UUIDField(...)), ('name', models.CharField(...)), ('created', models.DateTimeField()), ('updated', models.DateTimeField(...)), ('keywords_json', models.TextField()), ('model_bin', models.BinaryField()), ('article_ttl', models.FloatField(...)), ('timeliness', models.FloatField(...)), ('owner', models.ForeignKey(...)) ] However the key field is not present in the PostgreSQL database. This results in errors in any code that tries to access the Topic model objects from the database.