Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Double request logged from node request to Django endpoint
I'm trying to send a POST request to a django endpoint. It fails due to a 405. Inspecting the logs, it appears to receive the POST request, but then immediately followed by a GET request and returns a 405 as this is a POST only endpoint. I've stripped the fetching code back to the following js script: const fetchData = async() => { const response = await fetch("http://localhost:8000/api/auth/user", { method: "POST", body: { test: "test", }, headers: { "Content-Type": "application/x-www-form-urlencoded", }, }); if (!response.ok) { const text = await response.text(); console.log("error", response, text); } const json = await response.json(); console.log("json", json); }; fetchData(); It doesn't seem to matter what endpoint, or what method I send, it always logs a double request. What's also interesting, is if I send a PUT request, it logs a double PUT request, same for GET or even OPTIONS. However, for all POST requests, the second requests is always a GET. Again, it doesn't matter what endpoint I hit! I'm stumped I'm a JS dev, but I have access to the Django code if it would help to post the urls.py or any of the views from there? -
Error connection to server at "localhost", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
I'm trying to build API(with FastAPI) using python. I have installed python on windows WSL(ubuntu) and I have postgress on Windows. Now I'm trying to connect to Postgresssql via python code like below. but the connection is failing with Connection refused error code: try: conn = psycopg2.connect(host='localhost',database='fastapi',password='xxxx',cursor_factory=RealDictCursor) cursor = conn.cursor() print("Database connection was successfull") except Exception as error: print("Connetion to database has failed") print("Error", error) Error Connetion to database has failed Error connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I have gone through below link from from Stackoverflow but luck, can you please advice what could be the issue. How to connect to windows postgres Database from WSL Steps followed from the above link Add Windows Firewall Inbound Port Rule for WSL2 IP Addresses: Open Windows Defender Firewall with Advanced Security Click New Rule... Select Port for rule type Select TCP and for Specific local ports enter 5432 Select Allow the connection. Connecting from WSL2 won't be secure so don't select the secure option Select at least Public. Can select Domain and Private as well. I could only connect if Public was selected Name the … -
React - Django Rest Framework - Nested Form Items
I have a react form with an nested array of items. When i try to submit the form via DRF i receive a 400 status error detailing that the Item, Delivery Date, Description and Quantity fields are required. The models are setup so that i have a separate model for for the MaterialRequsitions and MeterialRequsitionItems On Submit Function (frontend) onSubmit={(values, { setSubmitting }) => { const formData = new FormData(); console.log('Material Requsition Form Values:', values); // Object.keys(values).forEach((key) => { // if ( key !== 'upload_documents' ){ // formData.append(key, values[key]); // } // }); formData.append('project', values.project); formData.append('title', values.title); formData.append('buyer', values.buyer); formData.append('date', values.date); formData.append('requested_by', values.requested_by); // values.items.forEach((item, index) => { // // Convert each item object to JSON string // formData.append(`items[${index}]`, (item)); // }); values.items.forEach((item, index) => { Object.keys(item).forEach(key => { formData.append(`items[${index}].${key}`, item[key]); }); }); // values.items.forEach((item, index) => { // Object.keys(item).forEach(key => { // formData.append(`items.${index}.${key}`, item.item); // }); // }); formData.append('user', userId); console.log(Array.from(formData.entries())); const uploadedFiles = uppy.getFiles(); uploadedFiles.forEach((file, index) => { console.log(`File ${index}: `, file); formData.append(`upload_documents[${index}]`, file.data, file.name); }); console.log('Form Data:', values); console.log(Array.from(formData.entries())); dispatch(addMaterialRequsition(formData)) .unwrap() .then((result) => { console.log('Material Requsition Added Sucessfully:', result); alert('Material Requsition Added Sucessfully'); onClose(); }) .catch((error) => { console.log('Failed to add Material Requsition:', error); }) .finally(() => … -
Django Custom Authentication Not Authenticating Users
I have a Django website, what I want is there to be separate user bases, one is User and another is Agent. Now Agent model does not extend the CustomUser Model. So that Agents can register themselves without being registered as a User first. When I register my Agents through AgentRegister form, my Agent passwords are being hashed properly which I can see in my Admin panel. Now the problem is, even when I enter correct Agent credentials in my AgentSignIn form, I can't log in as an Agent as it says "Please enter a correct username and password. Note that both fields may be case-sensitive." Same things happens when I enter correct User credentials into UserSignIn form. I can't sign in and it says "Please enter a correct username and password. Note that both fields may be case-sensitive." Note that both fields may be case-sensitive." How do I fix this? Neither login is working properly. My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') class Profile(models.Model): user = … -
How can I restrict the access to /admin only to staff users
I have admin site like this, urlpatterns = [ path('', include('defapp.urls')), path('admin/', admin.site.urls), I want to restrict the access only to the staff user. I tryied to do like this, from django.contrib.admin.views.decorators import staff_member_required urlpatterns = [ path('', include('defapp.urls')), path('admin/', staff_member_required(admin.site.urls)), However this shows the error 'tuple' object is not callable -
Django sum two columns with conditions using mysql raw query and render value to template
Please I need assistance on how to use Django to sum two columns with conditions using mysql raw query. Am just a newbie I need somtin select sum(amt), sum(qty) from table where transid=7 How can I use Django raw mysql query to solve it -
How can I setup a "can visit the link once and only once" kind of permission for my links in django?
I am creating a game webapp using on HTML CSS and Django. There is no JS involved so far because I dont know JS well enough to implement it in my app. I am not a webdeveloper either. I just know python and basic web design. Now to my issue: I have setup various tasks in different levels of the game. the user can visit these task to play them. But they should not be allowed to visit these tasks again after they've played it once. I was think of disabling the link after visiting once. Or maybe lock the link and make it unaccessable after visiting it one time and only be able to unlock it through the admin panel with a toggle or something. These are the ideas I have but don't know how to code. How can I implement this in django. I am also open to solutions on the front end with JS. Is this a case for django permissions or is it something else?. an image of the the levels dashboard I have tried targeting links using :visited pseudo class but not what I wanted. -
Creating a simple Many to Many seeding using Django Seed library
I am facing problem while creating a seeding for my Election and ElectionCandidate models in my Django project using Django-seed library. This is what I am trying to election3 = Election.objects.get(id=3) positions = Position.objects.all() random_position = random.choice(positions) # Seed the ElectionCandidate model # Seed the ElectionCandidate model with the related CandidatePosition model seeder.add_entity(ElectionCandidate, number, { 'first_name': lambda x: seeder.faker.first_name(), 'last_name': lambda x: seeder.faker.last_name(), 'biography': lambda x: seeder.faker.text(), 'date_of_birth': lambda x: seeder.faker.date_of_birth(), 'email': lambda x: seeder.faker.email(), 'contact_number': lambda x: seeder.faker.phone_number(), 'address': lambda x: seeder.faker.address(), 'image': None, 'is_incumbent': lambda x: seeder.faker.boolean(chance_of_getting_true=20), }) # Execute the seeding operation for ElectionCandidate inserted_pks = seeder.execute() election_candidate_ids = inserted_pks[ElectionCandidate] #add candidate posisitons to ElectionCandidates via positions.set method for election_candidate_id in election_candidate_ids: election_candidate = ElectionCandidate.objects.get(id=election_candidate_id) CandidatePosition.objects.create(election_candidate=election_candidate, position=random_position,election=election3) election_candidate.positions.set([random_position]) #election3.positions.set([random_position]) candidate_positions = CandidatePosition.objects.filter(election=election3) positions_for_candidate = [cp.position for cp in candidate_positions] election3.positions.set(positions_for_candidate) and Here are my relationships from django.utils import timezone from django.db import models from django.utils.timezone import localdate # from Candidate.models import ElectionCandidate class Position(models.Model): position_code = models.CharField(max_length=4, unique=True) position_name = models.CharField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.position_name # Create your models here. class Election(models.Model): election_type = models.CharField(max_length=20) election_date = models.DateField() title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) positions = models.ManyToManyField(Position, … -
Supervisor cannot start Gunicorn: ENOENT, problems with static files
Помогите, пожалуйста, возникли проблемы при деплое проекта на django (версия 4.2.1) с помощью gunicorn, nginx, supervisor Структура каталогов проекта: enter image description here enter image description here. Конфигурационные файлы для gunicorn и supervisor:enter image description here enter image description here supervisor выдаёт ошибку: supervisor: couldn't exec /root/workout/venv/bin/gunicorn: ENOENT supervisor: child process was not spawned Однако командой gunicorn myworkout.wsgi -b 172.18.0.1:8000 сайт запускается, но не загружаются статические файлы, ошибка: enter image description here В свою очередь, конфигурационный файл для nginx /etc/nginx/sites-available/default: enter image description here. Админка так же не закрывается... Подступалась к проблеме с разных сторон, проверила все пути, прописывала их по-разному, в конфигурационном файле nginx прописан include /etc/nginx/mime.types; -
Can create extended Field classes for Django Models introduce unexpected problems?
I'm starting a Django project and in my early design I'm thinking about extending the model's fields classes to add a new optional attribute belongs_to. It will be a list of elements that later would serve the purpose of filtering the object attributes. Example: # models.py class CustomCharField(models.CharField): def __init__(self, belongs_to: list=list(), *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.belongs_to = belongs_to class ModeloTest(models.Model): attr1 = CustomCharField(max_length=20, belongs_to=list(('type1', 'type2'))) attr2 = CustomCharField(max_length=10) attr3 = CustomCharField(max_length=10, belongs_to=list(('type1',))) attr4 = CustomCharField(max_length=10, belongs_to=list(('type2', 'type3'))) attr5 = CustomCharField(max_length=10, belongs_to=list(('type4'))) attr6 = CustomCharField(max_length=10, belongs_to=list(('type3',))) def fields_belongs_to(self, search_element): # 'id' Field is not Custom, doesn't have or need 'belongs_to' and can be ignored fields = [field for field in self._meta.fields if field.name != 'id'] filtered_fields = [field for field in fields if search_element in field.belongs_to] output = dict() for field in filtered_fields: output[field.name] = getattr(self, field.name) return output # views.py def main_view(request): m = ModeloTest.objects.first() context = { 'type1': m.fields_belongs_to('type1'), } return render(request, 'placeholder/main.html', context) With this design I can organize and classify fields in the Model and with the object.fields_belongs_to(search_element) method I get a dict of the Fields that belong to the type selected in search_element. If in the future I add a new … -
Problem loading image in user-uploaded images in Profile page
I am a beginner to Django (version = 5.0) and I have issue in viewing user-uploaded content on their profile page that is being rendered on HTML. I have installed Pillow library properly and I tried all methods but I can't seem to understand what the issue seems to be. views.py @login_required def user_profile(request): return render(request, "register_user/profile.html") urls.py from django.urls import path from register_user import views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static # url patterns app_name = 'register_user' urlpatterns = [ path("", views.index, name="register-index"), path("signup/", views.userRegister, name="register-user"), path("login/", auth_views.LoginView.as_view(template_name='register_user/login.html'), name="login"), # path("login/", views.login_user ,name="login"), path("profile/", views.user_profile, name="profile"), path("logout/", views.logout_user, name="logout"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = "default.jpg", upload_to='profile_pics') def __str__(self) -> str: return f"{self.user.username} Profile" settings.py STATIC_DIR = BASE_DIR / 'static' STATIC_URL = "static/" STATICFILES_DIRS = [STATIC_DIR,] # MEDIA MEDIA_ROOT = BASE_DIR / "media" MEDIA_URL = "media/" profile.html {% block content_block %} <div class="card border-light mb-3" > <img src="{{ user.profile.image.url }}" alt="Card image cap"> <div class="card-header">Username ~ {{ user.username }}</div> <div class="card-body"> <h5 class="card-title">{{user.first_name}} {{user.last_name}}</h5> … -
Project VueJS (frontend) with Django (backend): backend doesn't start (runserver/makemigrations/migrate) and doesn't give any error
I'm making a project with Django and VueJS. Last night I did some changes on the frontend and today I discard that changes on git, but they were all in Vue components. After that I tried to run both servers using Xampp (Apache and MariaDB/mySQL) and the backend doesn't run... You can see in the picture what is happening and the packages I'm using on the backend.When I try python manage.py migrate or python manage.py makemigrations (I didn't do any changes on the backend but just to see what happen) it also freezes, doesn't give any error message and I can't even cancel the process with ctr + c (but can end the runserver command).VisualStudio Code showing some of backend files, the libraries I'm using in venv and the problem I'm having I don't know what to do, I just restarted everything (including the computer) some times. No error is displayed and I don't have any idea what is happening. I was suppose to become in production this week and I don't understand even why this is happening. Ctr + alt + del also stop working the first time I tried to run this, but start working after restarting the … -
How to fix 502 Bad Gateway Nginx?
I get 502 when run my docker-compose version: '4' services: postgres: image: postgres:16 container_name: postgres restart: always volumes: - ~/.pg/pg_data/sch34nv:/var/posgresql/data env_file: - .env ports: - "5432:5432" networks: - backend_network redis: image: redis:latest container_name: redis restart: always env_file: - .env networks: - backend_network django: build: dockerfile: ./Dockerfile context: . container_name: django image: django restart: always depends_on: - postgres - redis volumes: - static_volume:/apps/django/staticfiles - media_volume:/apps/django/mediafiles env_file: - .env command: > bash -c "cd /apps/django/ && python3 manage.py collectstatic --noinput && python3 manage.py migrate && gunicorn -b 0.0.0.0:8000 sch34nv.wsgi:application" networks: - backend_network nginx: build: dockerfile: ./nginx/Dockerfile context: . container_name: nginx restart: always depends_on: - django volumes: - static_volume:/apps/django/staticfiles - media_volume:/apps/django/mediafiles env_file: - .env ports: - "${NGINX_PORT}:80" - "${NGINX_SSL_PORT}:443" networks: - backend_network networks: backend_network: volumes: static_volume: media_volume: FROM python:3.12.1 SHELL ["/bin/bash", "-c"] ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt update && apt -qy install gcc libjpeg-dev libxslt-dev \ libpq-dev libmariadb-dev libmariadb-dev-compat gettext cron openssh-client flake8 locales vim RUN useradd -rms /bin/bash sch34nv_user && chmod 777 /opt /run WORKDIR /apps/django RUN mkdir /apps/django/staticfiles && mkdir /apps/django/mediafiles && chown -R sch34nv_user:sch34nv_user /apps/django && chmod 755 /apps/django COPY --chown=sch34nv_user:sch34nv_user . /apps/django/ RUN pip install -r requirements.txt USER sch34nv_user EXPOSE 8000 … -
Django queryset contains a reference to an outer query
I have two related models in Django. class System(models.Model): system_id = models.IntegerField(primary_key=True) class DangerRating(models.Model): rating_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) system = models.ForeignKey('System', on_delete=models.CASCADE, related_name='danger_rating_units') value = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) I'm trying to use annotation to calculate the sum of values of the newest ten objects of DangerRating class for each system. I need this as an additional field 'danger_rating' to be used in a serializer. If I needed the sum of all values for each system it would be super easy, but since I only need ten newest ones I have to make a subquery, and I'm struggling to make it work. systems = System.objects.annotate( danger_rating=Subquery(DangerRating.objects.filter(system__system_id=OuterRef('pk')).order_by( '-timestamp')[:10].aggregate(rate_sum=Sum('value'))['rate_sum']) ) With this code I am getting an error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. What does this even mean? -
Django HttpResponseRedirect redirects me wrong
I want to redirect a link, for example mydomain.com/my_app/0 -------> redirect to : mydomain.com/my_app/finance but it redirects to mydomain.com/my_app/0/finance could you help me to fix this? views: from django.shortcuts import render from django.http import HttpResponse , HttpResponseNotFound , Http404 , HttpResponseRedirect articles = { 'finance' : 'finance page', 'sports' : 'sports page' } def news_view (request,topic): return HttpResponse(articles[topic]) def num_page_view(request,num_page): topics_list = list(articles.keys()) topic = topics_list[num_page] return HttpResponseRedirect(topic) urls: from django.urls import path from . import views urlpatterns = [ path('<int:num_page>/',views.num_page_view), path('<str:topic>/',views.news_view)] -
drf pagination duplicate data when applying a sorting
Why i am having a duplicate data when i tried to apply a sorting with django-rest-framework. I have this on my settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", "dj_rest_auth.jwt_auth.JWTCookieAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", "rest_framework.filters.OrderingFilter", ), "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10 } then i have this serializer class PersonListSerializer(serializers.ModelSerializer): org = OrgSerializer(many=False) # prompts = PromptResponseSerializer(read_only=True, many=True) # emails = EmailSerializer(read_only=True, many=True) custom_fields = PersonCustomFieldValueSerializer(many=True) tags = TagSerializer(many=True, default=[]) total_click_count = serializers.IntegerField(read_only=True) total_opened = serializers.IntegerField(read_only=True) total_reply = serializers.IntegerField(read_only=True) total_email_sent = serializers.IntegerField(read_only=True) scheduled_emails = serializers.SerializerMethodField() class Meta: model = Person fields = [ "id", "first_name", "last_name", "job_title", "company_name", "work_email", "company_website", "sent_emails", "last_contacted", "next_scheduled_email", "custom_fields", "org", "tags", "total_click_count", "total_opened", "total_reply", "total_email_sent", "got_data", "force_enable", "assigned_user", "status", "person_city", "state", "industry", "phone", "linkedin", "scheduled_emails", ] def get_scheduled_emails(self, obj): return EmailSerializer(obj.get_scheduled_emails(), many=True).data def get_user_created_emails(self, _obj): return _obj.emails.filter(created_by=self.context["request"].user) def to_representation(self, obj): representation = super().to_representation(obj) # Calculate sent_email_count sent_email_count = obj.emails.filter( status=0, created_by=self.context["request"].user ).count() total_click_count = sum( click_count or 0 for email in self.get_user_created_emails(obj) for click_count in email.click_tracking.values_list( "click_count", flat=True ) ) opened_emails = [ email for email in self.get_user_created_emails(obj) if hasattr(email, "trackings") and email.trackings.opened ] total_reply_count = ( self.get_user_created_emails(obj).aggregate( total_reply_count=Sum("reply_count__count") )["total_reply_count"] or 0 ) # Update the total_email_sent field in the representation representation['total_email_sent'] = sent_email_count … -
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0001_initial is applied before its dependency sites.0001_initial
Django==4.2.4 In production, postgresql. In local, sqlite(django's default) INSTALLED_APPS = [ 'snsapp.apps.SnsappConfig',My app 'allauth', 'allauth.account', 'allauth.socialaccount', 'bleach', 'widget_tweaks', 'django_ckeditor_5', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', Added 'django.contrib.sitemaps',Added ] I added site and sitemap to create a sitemap. How can I resolve this? I want to avoid deleting data and experiencing downtime because I've already released this product. -
Django login() does not work if you access the page not directly, but through a redirect from another site
If you go to the callback page directly in the browser, the authorization works and will be saved, but if you get to the callback through a redirect from another site (in my case Twitch), the authorization will not be saved, how can I fix it? class CallbackView(django.views.generic.RedirectView): def get_redirect_url(self, *args, **kwargs): # some checks # .... user = django.contrib.auth.authenticate( self.request, token=self.request.GET.get('code'), ) if user and user.is_active: # this code is triggered print(self.request.user.is_authenticated) # False django.contrib.auth.login( self.request, user, backend='twitch_auth.backends.TwitchOAuth2Backend', ) print(self.request.user.is_authenticated) # True return django.urls.reverse('twitch_auth:profile') django.contrib.messages.error(self.request, 'Error') return django.urls.reverse('homepage:home') class ProfileView(django.views.generic.TemplateView): template_name = 'twitch_auth/profile.html' def get(self, request, *args, **kwargs): print(request.user.is_authenticated) # True if open callback directly in the browser. False if it is redirect from Twitch return super().get(request, *args, **kwargs) In addition, the sessionid on the profile page is empty if Twitch redirects to the callback and not empty if the callback is called directly -
how to sort the drf Django Custom Integer Field in serializer
I have a code here which has a custom column in serializer with a query of a count and sum. class PersonListSerializer(serializers.ModelSerializer): org = OrgSerializer(many=False) custom_fields = PersonCustomFieldValueSerializer(many=True) tags = TagSerializer(many=True, default=[]) total_click_count = serializers.IntegerField(read_only=True) total_opened = serializers.IntegerField(read_only=True) total_reply = serializers.IntegerField(read_only=True) total_email_sent = serializers.IntegerField(read_only=True) scheduled_emails = serializers.SerializerMethodField() class Meta: model = Person fields = [ "id", "first_name", "last_name", "job_title", "company_name", "work_email", "company_website", "sent_emails", "last_contacted", "next_scheduled_email", "custom_fields", "org", "tags", "total_click_count", "total_opened", "total_reply", "total_email_sent", "got_data", "force_enable", "assigned_user", "status", "person_city", "state", "industry", "phone", "linkedin", "scheduled_emails", ] def get_scheduled_emails(self, obj): return EmailSerializer(obj.get_scheduled_emails(), many=True).data def get_user_created_emails(self, _obj): return _obj.emails.filter(created_by=self.context["request"].user) def to_representation(self, obj): representation = super().to_representation(obj) # Calculate sent_email_count sent_email_count = obj.emails.filter( status=0, created_by=self.context["request"].user ).count() total_click_count = sum( click_count or 0 for email in self.get_user_created_emails(obj) for click_count in email.click_tracking.values_list( "click_count", flat=True ) ) opened_emails = [ email for email in self.get_user_created_emails(obj) if hasattr(email, "trackings") and email.trackings.opened ] total_reply_count = ( self.get_user_created_emails(obj).aggregate( total_reply_count=Sum("reply_count__count") )["total_reply_count"] or 0 ) # Update the total_email_sent field in the representation representation['total_email_sent'] = sent_email_count representation['total_click_count'] = total_click_count representation['total_opened'] = len(opened_emails) representation['total_reply_count'] = total_reply_count return representation My fields with custom queries are : representation['total_email_sent'] = sent_email_count representation['total_click_count'] = total_click_count representation['total_opened'] = len(opened_emails) representation['total_reply_count'] = total_reply_count now How can i sort them with my modelviewset … -
Problem with Integrating Wagtail into a Django project
I built a test wagtail project with its own app that interact with Django. This is the GH repo: https://github.com/progettazionemauro/django-wiki-wag .What I want is to populate django admin panel with some data that after can be injected into wagtail app.I added in django admin panel the specific panel to feed the wagtail data but there is a problem. So in conclusion I have 2 routes: (Django admin) http://127.0.0.1/admin/ and (Wagtail admin): http://127.0.0.1/wagtail-admin) If I run python3 manage.py runserver at django level (Django admin) I am able to see the brand new admin panel integrated in Django admin, but I am not able to see the Wagtail Dashboard with the pages already created (I see a brand new Wagtail Dashboard)2) If I run python3 manage.py runserver at wagtail level (Wagtail admin) I am able to see wagtail pages I already created, but I am not able to see the Django admin panel with the the brand new admin pane created specific for wagtail (I see only Django admin panel)So I found the documentation and I cleaned the cache, restarted the server, but the problem persists and it seems not related to the memory or something like that. Moreover it seems related … -
If only CI fails, what kind of trouble could there be for django?
Overview The configuration file for github-actions is as follows. name: Django CI on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 1 matrix: python-version: [ 3.11 ] steps: - name: Checkout uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} cache: pip - name: Set up and run tests env: DB_ENGINE: django.db.backends.mysql DB_NAME: portfolio_db DB_USER: root DB_PASSWORD: root run: | # https://github.com/actions/runner-images/blob/main/images/linux/Ubuntu2204-Readme.md#mysql sudo systemctl start mysql mysql -u$DB_USER -p$DB_PASSWORD -e "CREATE DATABASE $DB_NAME;" python3 --version python3 -m venv venv source venv/bin/activate python -m pip install --upgrade pip python -m pip install -r requirements.txt python manage.py makemigrations register python manage.py migrate python manage.py makemigrations vietnam_research gmarker shopping linebot warehouse python manage.py migrate mysql -u$DB_USER -p$DB_PASSWORD -e "USE portfolio_db; SHOW TABLES;" export DJANGO_SECRET_KEY="$(base64 <<< "$RANDOM|TeStiNg|$RANDOM" | tr -d '\n')" python manage.py test detail This CI will fail at this time. The migration seems to be working fine and it seems failing in the testing process. https://github.com/duri0214/portfolio/actions/runs/7517515573/job/20463770730 It works fine on the VPS server, so I don't know why it's failing in CI. If anyone knows please help me -
convert data into queryset in django
I have data retrieved from databases using cursor in django, as the data is from more than one table that has a relationship. I want to convert the data to a quertset in order to use the annotite and order_by and values I tried to use the function list_to_queryset() from the convert_to_queryset library, but this function converts data into a queryset for only one Model, and I want to convert data, even if it is more than one Model. -
vps nginx ubuntu static and media files for port 8000
I deployed django project, everything work fine on 8000 port, except static and media directory. I want to use <my_ip>:8000 for backend and match static and media files. How can I match the folders for 8000 port? Here is my code now server { listen 80; server_name <my_ip>; access_log /var/log/nginx/example.log; root /home/ubuntu/client/build; location /media/ { root /home/ubuntu/api; expires 30d; } location /static/ { root /home/ubuntu/api; expires 30d; } location / { try files $uri $uri /index.html } } -
serve media files and static files in django
I have completed a Django project and now I want to run this project using Docker. I have created a container for Django and run the project. Everything was fine until I set the debug value to false. After that, static and media files cannot be found. Finally, using the whitenoise library, I managed to display the static files, but the media files still cannot be displayed. Now I want to do this using docker and nginx. Thank you for guiding me in this regard. -
Why python-telegram-bot is not working with celery?
I tried to use python-telegram-bot but it was not working while when I tried to use it out of celery asyncio with asds it was working well What is wrong with this code runing python-telegram-bot with celery on my django app: asyncio: async def send_telegram_message(message): from telegram import Bot bot = Bot(token=TELEGRAM_BOT_TOKEN) try: response = await bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message) print(f"Message sent successfully. Message ID: {response.message_id}") except Exception as e: print(f"Messageeeeeeeeee ID: {e}") # @shared_task async def check_deadline(): from telegram import Bot boards_url = f'https://api.trello.com/1/members/me/boards?key={TRELLO_API_KEY}&token={TRELLO_API_TOKEN}' boards_response = requests.get(boards_url) cards_url = f'https://api.trello.com/1/boards/6593cb5ef822ce42ea6645cd/cards?key={TRELLO_API_KEY}&token={TRELLO_API_TOKEN}' cards_response = requests.get(cards_url) cards = cards_response.json() await send_telegram_message('test') if __name__ == "__main__": import asyncio loop = asyncio.get_event_loop() loop.run_until_complete(check_deadline()) celery: def send_telegram_message(message): bot = Bot(token=TELEGRAM_BOT_TOKEN) try: response = bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message) print(f"Message sent successfully. Message ID: {response.message_id}") except Exception as e: print(f"Message ID: {e}") @shared_task def check_deadline(): print('check_deadline task started!') boards_url = f'https://api.trello.com/1/members/me/boards?key={TRELLO_API_KEY}&token={TRELLO_API_TOKEN}' boards_response = requests.get(boards_url) cards_url = f'https://api.trello.com/1/boards/[baordId]/cards?key={TRELLO_API_KEY}&token={TRELLO_API_TOKEN}' cards_response = requests.get(cards_url) cards = cards_response.json() send_telegram_message('asdsadasd') I was expecting bot to send message correctly with the celery beat?