Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am unable to load data from my custom package's database in to my running project(project is running in docker), it shows me following error
I have a custom package name "xyz", i installed it in my project running in docker, but its unable to load data from databse of package "xyz", it show me following error. django.db.utils.ProgrammingError: relation "xyz" does not exist even while executing makemigrations and migrate command, it shows a same error django.db.utils.ProgrammingError: relation "xyz" does not exist although i have intial migrations file in my docker container. how i can access my database of my package.? i try makemigrations and migrate command, but same error. -
django.db.utils.ProgrammingError: relation does not exist during installing external packages using pip
I have created an django resuable app. It has an model file contain following modle models.py from django.db import models class KnApiGatewayToken(models.Model): access_token = models.TextField() refresh_token = models.TextField() There is 1 migration file from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='KnApiGatewayToken', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('access_token', models.TextField()), ('refresh_token', models.TextField()), ], ), ] The resuable app i.e. the django project is working perfectly. I can see the models in the admin side also. Now i have installed this package ( django resuable app ) in another django project using following command pip install /path/to/package/dist/package.tar Package get installed successfully, but during runserver, it is giving following error django.db.utils.ProgrammingError: relation "kn_python_amazon_ad_api_knapigatewaytoken" does not exist LINE 1: ...on_ad_api_knapigatewaytoken"."refresh_token" FROM "kn_python... I have tried running makemigration and migrate command too, but still it gives me the same error. -
Convert datetime string to with timezone in django based on active time zone
I am reading a get request and adding the data to db. import dateutil.parser as dt date_string = '2023-12-14 08:00:00' date_obj = dt.parse(date_string) It shows warning RuntimeWarning: DateTimeField RequestLab.end_time received a naive datetime (2023-12-14 08:00:00) while time zone support is active. Is there any way i can convert this to date object with time zone from django.utils import timezone curr_timezone = timezone.get_current_timezone() and store in the db.. I tried using various methods like datetime_obj_test1 = date_obj.replace(tzinfo=curr_timezone) datetime_obj_test2 = date_obj.astimezone(curr_timezone) But these 2 are changing the time i.e for timezone = "Asia/Kolkata" datetime_obj_test1 = 2023-12-14 08:00:00+05:53 datetime_obj_test2 = 2023-12-14 19:30:00+05:30 I am expecting this as output: 2023-12-14 08:00:00+05:30 -
NoReverseMatch for submitting my form on my profile page
I have a blog project for a assignment and i have all functionality except for my user profiles editing and deleting. I have created the profile page and ability to edit the page. When i then submit my update request, i can see that it submits the change as after i get the error the profile page is updated. I am getting this error and i know it is due to the redirect but i cannot figure out for the life of me how to just redirect back to the user profile. I have tried to just use a httpredirect or reverse and now using reverse_lazy as that has worked fine for blog posts and comments and edits. This is my error and code bellow. I belive it is down to the get_success_url and am hoping that someone has had this error or knows the best fix for this. Thank you NoReverseMatch at /1/edit_profile_page/ Reverse for 'show_profile_page' with no arguments not found. 1 pattern(s) tried: ['(?P[0-9]+)/profile/\Z'] Views.py class EditProfile(LoginRequiredMixin, SuccessMessageMixin, UserPassesTestMixin, generic.UpdateView): model = Profile template_name = 'edit_profile_page.html' form_class = ProfileForm success_message = 'Updated Profile' def get_success_url(self): return reverse_lazy('show_profile_page') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def test_func(self): profile … -
Axios response interceptor times out with put data, but works without put data
Why does the response interceptor not fire for 401 when I use data in put (django server shows 401 due to access_token being outdated, but response interceptor fires timeout of 5000ms exceeded), however if I pass nothing (no data arg in put) fires the response interceptor with 401 as expected. This code does not trigger 401 in the response interceptor const updateProfile = async ({ _isPrivate, _color_scheme, _avatar }) => { var data= { first_name: first_name, last_name: last_name, venmo_username: venmo_username, about: about, private: _isPrivate, color_scheme: _color_scheme, avatar: _avatar, city: city, country: country, phone_number: phone_number, }; axiosConfig .put(`/api/users/${user.id}/`, data) .then((res) => { if (res.status === 200) { setUser(res.data); updateUser(res.data); } else if (res.status === 202) { var msg = res.data.data; Alert.alert(msg); } }) .catch((res) => { Alert.alert("Error during User Profile update. " + res); }); }; Eliminating the parameter does call the 401 in response interceptor const updateProfile = async ({ _isPrivate, _color_scheme, _avatar }) => { axiosConfig .put(`/api/users/${user.id}/`) .then((res) => { if (res.status === 200) { setUser(res.data); updateUser(res.data); } else if (res.status === 202) { var msg = res.data.data; Alert.alert(msg); } }) .catch((res) => { Alert.alert("Error during User Profile update. " + res); }); }; My interceptors look like this. … -
Getting CSRF verification failed. Request aborted. on a Django forms on live server
Hello I am learning Django i write a app and publish it in AWS EC2 instance with gunicorn and ngnix on local environments everything works fine but in production on every submit on forms i get this 403 Error : Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. iam sure in templates every form have {% csrf_token %} and this is my setting.py file of django app: import os from pathlib import Path from decouple import config BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = config("DJANGO_SECRET_KEY") SITE_ID = 1 DEBUG = False ALLOWED_HOSTS = ["winni-furnace.ca", "www.winni-furnace.ca"] CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = '.winni-furnace.ca' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', # local 'accounts.apps.AccountsConfig', 'blog.apps.BlogConfig', 'mail_service.apps.MailServiceConfig', 'messages_app.apps.MessagesAppConfig', 'offers.apps.OffersConfig', 'pages.apps.PagesConfig', 'projects.apps.ProjectsConfig', 'score.apps.ScoreConfig', 'services.apps.ServicesConfig', # 3rd 'taggit', "django_social_share", "whitenoise.runserver_nostatic" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , '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 = 'app.wsgi.application' AUTH_USER_MODEL = "accounts.CustomUser" LOGIN_REDIRECT_URL = "pages:index" LOGOUT_REDIRECT_URL = "pages:index" # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { … -
1 hour difference between Mariadb timestamp and Django DateTimeField
I have a simple Django project that uses an existing mariadb database running at localhost as the default database. In the database timestamps are stored correctly, in Django however they are one hour later. I created a simple database called test with a table called time: CREATE DATABASE test; CREATE TABLE time (time_id INT PRIMARY KEY AUTO_INCREMENT, time TIMESTAMP); INSERT INTO time (time) VALUES (NOW()); Then I started a Django project called testproject with an app called testapp. I set the database settings and defined the following model: class Time(models.Model): time_id = models.AutoField(primary_key=True) time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'time' After running migrate, when I open python manage.py dbshell, I get: MariaDB [test]> SELECT CONVERT_TZ(`time`, @@session.time_zone, '+00:00') AS 'utc_datetime' FROM time; +---------------------+ | utc_datetime | +---------------------+ | 2023-12-27 20:40:46 | +---------------------+ 1 row in set (0.000 sec) which ist correct. However when I do the same thing with python manage.py shell, I get: >>> from testapp.models import Time >>> Time.objects.latest('time').time datetime.datetime(2023, 12, 27, 21, 40, 46, tzinfo=datetime.timezone.utc) I noticed this in a more complex project but was able to reproduce it in this very simple example. I live in the timezone CET, in the settings.py … -
How to find the desktop or user path?
I want you to help me to find this path. For example, I work on a project like Django. Then to be able to access the client desktop I need to find that path so I can put the required files directly on it. Although I know Django gives me an address, I only gave an example. I didn't make any effortand just came here hopingto find an answer and asked my question. That's it! -
Docker Compose + Django CLI commands: django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I have a django + vue project built using django cookie cutter with docker. Because I've done this with docker, after starting my containers, I can't use the normal python manage.py command command. I instead get this error message django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable. I have searched everywhere to figure out how to fix this but I can't find anyone with a fix for this. So my question is: Is there a fix for the DATABASE_URL error I am getting? -- Steps to reproduce are follow these cookie cutter django with docker instructions and try to run python manage.py migrate. -
I have an issue with my smtp relay server while sending email from Godaddy website
Hello everyone i have a website where Iam sending an outgoing mail from my website to other email accounts during registration for confirming. I am unable to send this email and even after talking to godaddy customer service multiple times, the issue remains unresolved. Iam using Django and these are my settings. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = relay-hosting.secureserver.net EMAIL_PORT = 25 EMAIL_USE_TLS = False # GoDaddy's relay server does not use TLS/SSL EMAIL_HOST_USER = '' # Typically, no username/password is required for internal relay EMAIL_HOST_PASSWORD = '' EMAIL_USE_SSL = False [ Error Screenshot 1 Error Screenshot 2 current_site = get_current_site(request) mail_subject = 'Activate your blog account.' from_email_address = 'noreply@indiaengineerskills.com' message = render_to_string('network/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user_imp.pk)), 'token': account_activation_token.make_token(user_imp), }) to_email = user_email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() The above screenshots are error snippet and code snippet for sending mail. Any help would be appreciated I have tried talking to godaddy about this but they said that their testscript was working fine... -
Accessing Dictionary in jinja2
{% for blog in data %} {% with current_ids=blog.blog_id %} {{ like_ids }} {{ current_ids }} {{ like_ids['bar'] }} {% endwith %} {% endfor %} in above code {{ like_ids }} prints {'foo': [], 'bar': [<User: foo@bar.com>]} {{ current_ids }} prints foo || bar {{ like_ids['bar'] }} throws error "Could not parse the remainder: '['bar']' from 'like_ids['bar']'" i tried like_ids.bar and it prints [<User: foo@bar.com>] but, like_ids.current_ids doesn't print anything tried set instead of with and the problem still exists -
i have tried to install django several times and every time i get this
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023991896320>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000239918965F0>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000239918967A0>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023991896950>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023991896B00>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/ba/c7/61b02c0ef9e129080a8c2bffefb3cb2b9ddddece4c44dc473c1c4f0647c1/Django-5.0-py3-none-any.whl.metadata (Caused by ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000023991896CB0>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')) -
Update a Cache value without changing original timeout in Django
I am basically creating a cache key at a certain point with a timeout of a week. cache.set("myKey",myValue,timeout=604800) I'd like a way to update this cache value without changing the original timeout value. According to the documentation, if I pass None the value is cached forever, and if I dont pass anything it defaults to what I have in my settings. cache.set("myKey",myValue,timeout=?) So how could I do this? -
Trouble with service account's json stored in Google Secret Manager (Only when deployed)
I've got a problem that I just can't seem to work out. I am running a django project, deploying via GCP App Engine. I have taken all my sensitive key/token data from my settings file and placed them in my Google Secret Manager. That works fine, both locally and deployed. HOWEVER... When I try to do the same from my service account json, the project only runs locally. When I deploy, there is no error in deployment, but the site times out. The error log reads a bunch of: "Process terminated because the request deadline was exceeded. Please ensure that your HTTP server is listening for requests on 0.0.0.0 and on the port defined by the PORT environment variable. (Error code 123)" My app.yaml is configured as: runtime: python39 instance_class: F2 entrypoint: gunicorn -b :$PORT gondolaProject.wsgi:application automatic_scaling: target_cpu_utilization: 0.65 env_variables: DJANGO_SETTINGS_MODULE: "gondolaProject.settings" CLOUD_SQL_CONNECTION_NAME: "placeholder-401815:us-central1:to-be-announced" beta_settings: cloud_sql_instances: "placeholder-401815:us-central1:to-be-announced" Any ideas what might be causing this behavior??? Thanks in advance :) -
I am getting error 405 when running this Django program via drf
This code is for user registration through API, but when I try to test it with Postman, it gives error 405. Can you test the program and tell me where the problem is? I first created an account, then added it to my project settings and URL You can see the rest of the work below views: from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import UserRegisterSerializer class UserRegister(APIView): def post(self, request): ser_data = UserRegisterSerializer(data=request.POST) if ser_data.is_valid(): User.objects.create_user( username=ser_data.validated_data['username'], email=ser_data.validated_data['email'], password=ser_data.validated_data['password'], ) return Response(ser_data.data) return Response(ser_data.errors) serializers: class UserRegisterSerializer(serializers.Serializer): username = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(required=True, write_only=True) URLs: from . import views app_name = 'accounts' urlpatterns = [ path('register/', views.UserRegister.as_view()), ]``` and error: [1]: https://i.stack.imgur.com/ckM9c.png -
Django Custom Authentication Not Authenticating Custom User
So I am trying to build a website using Django where there are two separate user bases, one is user and the other is agent. Now I imported User from from django.contrib.auth.models import User and have a separate model for Agent. What I want is for there to be different login urls for users and agents. An agent can be an agent without having to be registered as a user. Now I have tried this code, and what this does is after trying to log in using agent credentials, it logs in and returns the correct html page but doesn't even authenticate if those credentials are right or wrong. Like the agent_login is still logging me in even after providing it with the wrong credentials. Now I want to know what the problem is and how to fix it so that it works properly. My models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = … -
Django reverse Accessor Clash - Related Name not working
I am receiving an error for 'reverse accessor' clashes when trying to create a models for my Django app. Based on what I have seen, supposedly, assigning a unique 'related name' to the fields solve the issue. However, I have tried this and it still occurs. I have also tried using '%(app_label)s_%(class)s_related' as a related name as well, but this has not worked. I am struggling a bit to understand how this all works - is anyone able to help me out? Will provide code below, thanks class TradeOffersManager(models.Manager): def create_trade_offer(self, sender, reciever, sending_item, recieving_item): trade_offer = self.create(sending_item=sending_item, recieving_item=recieving_item) trade_offer.sender.set(sender) trade_offer.reciever.set(reciever) return trade_offer class TradeOffers(models.Model): sender = models.ManyToManyField(User) sending_item = models.ForeignKey(TradePost, on_delete=models.CASCADE, related_name="sending_item_name") reciever = models.ManyToManyField(User) recieving_item = models.ForeignKey(TradePost, on_delete=models.CASCADE, related_name="recieving_item_name") objects = TradeOffersManager() -
Cannot deploy Django app to App Runner: TypeError: 'staticmethod' object is not callable
I have a Django 5 application that I'm trying to deploy to AWS App Runner. I've followed the instructions on here and also here in order to make a deployment to App Runner using MySQL as the DBMS. I had to downgrade my Django version because App Runner only supports up to Django 4.2.8. I reinstalled every package into my venv in order to get an updated version of the requirements file. Locally, the app works just fine, but whenever I make a deploy to App Runner, I get this error: I've tried looking it up, but I cannot find a reference that helps. What could be going wrong? -
How to add optional filters in Django exta actions
I have a ViewSet with extra action shown below class Parent: queryset = Model.objects.all() serializer_class = ParentSerializer ... ... @action(detail=True, methods=["get", "post"], serializer_class=SomeSerializerclass) def extra(self, request, *args, **kwargs): ... I want to add few optional query parameters to this extra action endpoint like: parent/1/extra/?name=somename and this will filter the data for this name if request.method is GET. Also, this query param can be multiple like: parent/1/extra/?name=somename&?surname=foo How can I achieve this? -
I got an error of Internal server and integrity error how can i solve this
I got an error when i want to fetch value from html page to ajax, and i got null. view.py `def placeorder(request): if not 'userid' in request.session: return redirect('login') if request.method == 'POST': print("hii") neworder = Order() neworder.user_id = request.session['userid'] neworder.fname = request.POST.get('firstname') neworder.lname = request.POST.get('lastname') neworder.address = request.POST.get('address') neworder.city = request.POST.get('city') neworder.state = request.POST.get('state') neworder.country = request.POST.get('country') neworder.zipcode = request.POST.get('code') neworder.phone = request.POST.get('phone') print(neworder.fname) #PAYMENT MODE: # neworder.payment_mode = request.POST.get('payment_mode') neworder.payment_id = request.POST.get('payment_id') cart = Cart.objects.filter(user=request.session['userid']) cart_total_price = 0 for item in cart: cart_total_price = cart_total_price + item.product.Price * item.quantity neworder.totalprice = cart_total_price neworder.save() neworderitems = Cart.objects.filter(user=request.session['userid']) for item in neworderitems: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.Price, quantity=item.quantity ) #Decrease the quantity from order stocks: # orderproduct = Products.objects. Cart.objects.filter(user=request.session['userid']).delete() messages.success(request, "Your order is placed!") return redirect("home")` js file: `$(document).ready(function(response){ $('.paywithrazorpay').click(function (e){ e.preventDefault(); var fname = $("[name='firstname']").val(); var lname = $("[name='lastname']").val(); var address = $("[name='address']").val(); var city = $("[name='city']").val(); var state = $("[name='state']").val(); var country = $("[name='country']").val(); var code = $("[name='code']").val(); var phone = $("[name='phone']").val(); var token = $("[name='csrfmiddlewaretoken']").val(); if(fname == "" || lname == "" || address == "" || city == "" || state == "" || country == "" || code == "" || phone == ""){ // … -
Adding a red star next to the label and deleting this message:This field is required
I want it to appear next to the red star label in the form. However, with these codes, an asterisk appears and the message I mentioned is deleted, but: 1- The symbol like the unordered list symbol is displayed on the top of the label. 2- Fields that are text and Boolean have problems . 3- Based on the field that is text, it is not recognized and I have to put a char field. 4- It comes both next to the label and next to the star field. 5- I want the username to be automatically taken from the user name and cannot be changed. However, if The sixth line of the class is deleted, a drop-down menu will appear and the user can choose a name, and if it is not deleted, the form will not be submitted. (In this context, I tried other codes and it didn't work. They are also commented). views.py: def create_product(request): form = ProductForm(request.POST, request.FILES) if request.method == 'POST': user = request.user if user.is_authenticated: if form.is_valid(): form.save() return redirect('index') else: form = ProductForm() return render(request, 'auctions/create_product.html', {'form': form}) html: {% block body %} <h2>Create New Product</h2> {% if user.is_authenticated %} <form id="cform" method="post" … -
Excluding YouTube links from urlize filter and handling iframe tags in Django template
I'm facing an issue in my Django template where I want to exclude YouTube links from the django urlize filter and ensure that the remaining content, including YouTube videos embedded with iframe tags, is properly displayed. Here's a simplified version of my template and view here's the template <div class="comment-body">{{comment.body|safe|linebreaksbr|urlize}}</div> here is the way i converted the youtube link to iframe: yt_link = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I) yt_embed = '<iframe width="460" height="215" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>' def convert_ytframe(text): return yt_link.sub(lambda match: yt_embed.format(match.groups()[5]), text) How can I modify my template to exclude YouTube links from the urlize filter How can I ensure that the remaining content, including YouTube videos, is properly displayed and the iframe tags are not affected by the urlize filter -
Having gunicorn binding to the web itself and to pgadmin
When intalling web pgdamin4 on a vps there are things to do besides pip installing. Namely you need to add another location sections in the nginx file location / { proxy_pass http://unix:/tmp/pgadmin4.sock; include proxy_params; } but then you need to bind gunicorn to this address. However, gunicorn is already binding to the web url like this and it works fine: ... ... SOCKFILE=/home/boards/run/gunicorn.sock exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- and my web is running on supervisor's support, so the question here is how to do that extra binding to that address. namely: gunicorn --bind unix:/tmp/pgadmin4.sock --workers=13 --threads=25 --chdir ~/environments/my_env/lib/python3.10/site-packages/pgadmin pgAdmin:app as nginx is giving me bad gateway 502 error and that is precisely for that, because it can't find the second bind address for the www.myweb.com/pgadmin, however I get no error when going to www.myweb.com -
I'm getting the error "Cannot unpack non-iterable object" in Django app
I've looked through a few topics with questions almost the same as mine but none of them really helped. The thing is that I'm writing a training Django app where I'm storing info about music albums that I like. Currently I'm adding a form via which I want to add albums to the database (instead of the standard form within "/admin/"). So, the models I have are quite simple: from django.db import models class Genre(models.Model): name = models.CharField(max_length=30) class Meta: verbose_name_plural = "genres" def __str__(self): return self.name class Album(models.Model): author = models.CharField(max_length=100) name = models.CharField(max_length=100) release_date = models.IntegerField() cover = models.ImageField(upload_to="media") genres = models.ManyToManyField("Genre", related_name="album") def __str__(self): return self.name As you can see, Album and Genre classes are related to each other via ManyToManyField. The form responsible for adding an album to the database looks like this: from django import forms from .models import Genre CHOICES = Genre.objects.all() class AddAlbumForm(forms.Form): author = forms.CharField(label="Album's author", max_length=100) name = forms.CharField(label="Album's name", max_length=100) release_date = forms.IntegerField(label="Album's release year") genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHOICES) cover = forms.FileField() All in all, the form is operational, except for the line with "genres" variable (if I comment it, the form works just fine). The related view looks like … -
Move django model field from nested models to the 'main' model
I have 2 django models linked like this: class ModelA(models.Model): id = models.UUIDField(primary_key=True) # some other fields here class ModelB(models.Model): modela_id = models.UUIDField(primary_key=True) unique_field = models.FloatField() order = models.IntegerField(primary_key=True) random_field = models.FloatField() and serializers for these 2 models: class ModelASerializer(serializers.Serializer): id = serializers.CharField(help_text="Measurement ID") # some other fields here b_objects = ModelBSerializer(many=True) classModelBSerializer(serializers.Serializer): id = serializers.CharField(source="order") random_field = serializers.FloatField() unique_field = serializers.FloatField() I want to write an endpoint that will return the list of ModelA entities and all the related ModelB objects to the particular ModelA object. I have this currently, it works just fine: ModelA.objects.prefetch_related("b_objects").all() which returns a list of objects like this one: { "id": "92eb8314-3f26-4bf6-8cc0-83d2935434d9", ### modelA fields here "b_objects": [ { "id": "1", "random_field": 1.0, "unique_field": 0.1 }, { "id": "2", "random_field": 5.0, "unique_field": 0.1 } ] } What I want here is to move "unique_field" from inner level to the level of modelA so that it would return: { "id": "92eb8314-3f26-4bf6-8cc0-83d2935434d9", "unique_field": 0.1 ### modelA fields here "b_objects": [ { "id": "1", "random_field": 1.0 }, { "id": "2", "random_field": 5.0 } ] } It's 100% that all values of unique_field will be equal in all the b_objects within particular modelA objects. I tried to add …