Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
why the path of static files change when I add slash (/) at the end of the url's path in django
Why when I use slash in url's path the path of static files get changed: Below is main project urls.py file: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app_home.urls')), path('blog', include('app_blog.urls')), ] if settings.DEBUG == True: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and forexample if I add slash at the end of blog the path of static files get changed: path('blog/', include('app_blog.urls')), therefore the path if I add a slash will be: http://127.0.0.1:8000/**blog**/static/vendor/bootstrap/js/bootstrap.bundle.min.js (and none of static files are functional because the path is changed) instead of the correct path which is: http://127.0.0.1:8000/static/vendor/bootstrap/js/bootstrap.bundle.min.js -
Docker django project problem with mysqlclient for using mysql
I have problem with docker container build process with docker compose, the django project that i want to build, has problem in mysqlclient library installation and usage, I use pip cache for faster build process and lower internet download traffic, but in this way the mysqlclient library seems that did not completely installed : If i run a db related command this error shown : Or inside container : If i uninstall it and install it again without using cache, the problem goes away : I use python:3.11-slim image and install all dependencies before going for this : RUN apt install apt-utils python3-dev \ default-libmysqlclient-dev pkg-config gcc -y --no-install-recommends The process of building this specific library is different when i not use cache and after that everything is works fine . why !? mysqlclient==2.2.1 host : ubuntu 23.10 django 4-5 -
When i click back on django root url it gives error page not found
Hello everyone i face problem in djnago ,When i click back on root url,in urls.py it give error page not found.plz answer my question quickly. I only add html template in djnago, all pages works properly but when we click back on root url it give error of page not found -
I m not able to send Json data to Django views.py , im trying Ajax for this but its not working , also its show CSRF error
I'm facing an issue with CSRF verification in a Django project when making an AJAX POST request. Here's a simplified version of my code: **registration.html *** <form method="POST" onsubmit="return validateForm()"> (----this revieves the data------) {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <label for="password">Password:</label> <input type="password" id="password" name="password" required /> <input type="submit" value="Register" name="createuser"/> </form> </div> </div> <script> let URLd ="{% url 'defaultpg' %}" let nameInput = document.getElementById("name"); let emailInput = document.getElementById("email"); let passwordInput = document.getElementById("password"); (------below funtion validates it -----) function validateForm() { var csrfToken = $("input[name='csrfmiddlewaretoken']"); let nameValue = nameInput.value; let emailValue = emailInput.value; let passwordValue = passwordInput.value; let isNameValid = /^[a-zA-Z]+$/.test(nameValue); let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue); let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(passwordValue); if (isNameValid) { if (isEmailValid) { if (isPasswordValid) { alert("Successful"); $.ajax({ type: "POST", url: '/defaultpg', headers: {"X-CSRFToken":'{{ csrf_token }}'}, data: { "name": nameValue, "email": emailValue, "password": passwordValue, 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]") }, dataType: "json", success: function (data) { // any process in data alert("successful"); }, error: function () { alert("failure"); } }); } else { alert("Password must contain letters, capital letter, small letter, special character, and numbers with a length above 8"); } } else { alert("Please enter a … -
How to Constraint Date Range From Intersection
I have a model defined like below class Event(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) start = models.DateField() end = models.DateField() I would like to setup constraints such that time span of each room's event is not intersect with each other. For example: Event 1: Room A, date: [2024-01-01, 2024-01-05]; Event 2: Room A, date: [2024-01-08, 2024-01-12]; <- Fine Event 3: Room A, date: [2024-01-04, 2024-01-07]. <- NOT fine Event 3 is not fine because Room A is already occupied by Event 1 on Jan 4th and Jan 5th. How can I achieve this with model constraints? -
OperationalError at / no such column: app_post.category_id
I'm working on a Django project (like a blog), and I'm bit struggling with when I edit models in live project (meaning that I cannot lose my db). In this case originally I didn't have category to my posts, now I have added but there is an issue. When I apply makemigrations and migrate, I get this: OperationalError at / no such column: learning_app_post.category_id Tried also this by some internet sources: python manage.py migrate --fake learning_app zero ... and when I migrate again, I get django.db.utils.OperationalError: table "learning_app_post" already exists. So I end up in the loop, any ideas here? This is my models.py class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") category_name = models.CharField(max_length=255, verbose_name="Category name") parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True) def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): self.clean() super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.category_name class Post(models.Model): category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, blank=True, null=True, default=None) ... #rest of the post model Thanks in advance! -
Django rest framework is providing the wrong parameters to custom permission class
I'm having an issue where Django Rest Framework's custom permission system is treating my custom permissions' methods like they are classmethods or staticmethods. When hitting a breakpoint in the permission method: def has_permission(self, request, view=None): self is an instance of request instead of an instance of the permission class request is an instance of view and I had to put view=None because it was crashing with missing parameter errors Have I configured it wrong somehow? My IsEmailVerified permission used as a default permission has been working as expected for a month, but when adding custom permissions more programmatically I get errors. File "/app/api/permissions.py", line 50, in has_permission user = request.user ^^^^^^^^^^^^ AttributeError: 'ExampleViewSet' object has no attribute 'user' settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'api.permissions.IsEmailVerifiedPermission', ), . . . } permissions.py class IsEmailVerifiedPermission(BasePermission): def has_permission(self, request, view=None): return request.user.email_verified def has_object_permission(self, request, view=None, obj=None): return request.user.email_verified class UserCreated(BasePermission): def has_permission(self, request, view=None): # While debugging the parameters don't line up: # self is an instance of request # request is an instance of view # and I had to put view=None because it was crashing with missing parameter errors def has_object_permission(self, request, view=None, obj=None): # … -
nginx configuration for vps server react and django app
I really new with deploy, but finnally I've got some results: I run my react app in <my_ip>:3000 I run my django project in <my_ip>:8000 What I need is: run <my_domain_name> react app run <my_domain_name>/admin django app I faced with the problem with nginx configuration. I try at list start one app, but got 502 error. sudo nano /etc/nginx/sites-available/default/ server { listen 80; server_name my_domain.com; access_log /var/log/nginx/example.log; location /media/ { root /home/ubuntu/server; expires 30d; } location /static/ { root /home/ubuntu/server; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } I checked /etc/hostname is test I add this hostname to /etc/hosts 127.0.0.1 localhost 127.0.1.1 test 127.0.1.1 unassigned-hostname.unassigned-domain unassigned-hostname # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters Restart nginx successfully done, but I still see my projects only on 3000 and 8000 posts. How can I fix it? sudo service nginx restart Also how correctly add the react app into nginx settings? One more: I run my react app with command npm start. But when I close the terminal, 3000 port also stop working. How can I fix this issue? For django … -
Backend not working after pulling a commit from history that worked
I have my Authentication System backend on Django and Frontend on React. I was trying to implement a new API endpoint and suddenly my authentication system is not working (Auth system made with Djoser). I can assure you that before moving on to the new API I tested the Authentication System API's with POSTMAN and everything worked fine. I am using postgres db. I pulled a git commit from history that worked for sure, and still not working. One of my friends is a collaborator and for him is working, he force pushed and overwritten everything but for me for some reason it doesn't work anymore. When trying to Sign Up (or Login) I get this error POST /auth/users/ HTTP/1.1" 400 29 POST /auth/users/activation/ HTTP/1.1" 400 50 POST /auth/jwt/create/ HTTP/1.1" 401 63 Here is my 2 models from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.dispatch import receiver # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = … -
Heroku - Django - Translation not working in production
I am trying to translate some static text with a Django app. It works on my local, but not on production. I use Heroku. What I did: After doing some research it seems to be partly because .mo is in my .gitignore.py. However, I read a few times that this should remain as such and instead automate compile messages in an app.json file. Which is what I did below: app.json { "scripts": { "release": "python manage.py compilemessages" }, } With the 'gettext' buildpack added to Heroku, I did manage to see a large push of lines contained in my local .mo file on the production logs. However, I cannot seem to be able to render them. I can clearly see the .mo files when running: heroku run bash -a appname find . -name "*.mo" Questions: Should I simply remove the .mo from .gitignore to fix the issue? Am I right to continue on the current path and find a solution without removing .mo from .gitignore? -
Issue with API pagination in django
the problem I'm having is that when I try to click next in the pagination that I did, the link param name "dataType" dosen't stays and it resets to none value, please help. I'm Using django I did some debug and appears like this: [13/Jan/2024 13:33:57] "GET /search/?query=Spaghetti&dataType=&page=27 HTTP/1.1" 200 9901 query: Spaghetti, dataType: Branded, page: 1 [13/Jan/2024 13:34:06] "GET /search/?query=Spaghetti&dataType=Branded HTTP/1.1" 200 7304 query: Spaghetti, dataType: , page: 2 And this is my html: <!-- PAGINATION LINKS --> <div class="pagination"> <span class="step-links"> {% if pagination.current_page > 1 %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page=1">&laquo; first</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'-1' }}">previous</a> {% endif %} <span class="current"> Page {{pagination.current_page}} of {{pagination.total_pages}}. </span> {% if pagination.current_page < pagination.total_pages %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'1' }}">next</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{pagination.total_pages}}">last &raquo;</a> {% endif %} </span> </div> I don't know if the issue is from the views.py or the html or the forms.py, apreciate your responses!!! I have tried changing the links in the html and nothind I did worked. -
Django ecommerce modeling- how to model product/service options?
I am currently facing a dilemma where we are creating a service which can be used for billing or ecommerce-type applications where products and services are modeled and can be sold. I am working on Services, which have ServiceOptions. The Services are assigned to Businesses, which will each contain a unique combination of Services and ServiceOptions. Because of this, I have represented a Service which all possible ServiceOptions point to as a foreign key relation, creating a BusinessService to assign the unique variants to a Business. However, I am currently unable to understand how to model the relationship between ServiceOptions and the BusinessService. My current service models are as follows: class Service(models.Model): name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class ServiceOption(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class BusinessService(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) price_override = models.IntegerField(null=True) is_active = models.BooleanField(default=False) activation_date = models.DateTimeField(default=timezone.now) Here we create a unique entity tying the Service to the Business, but this is not sufficient to represent the ServiceOptions, as the BusinessService.service.serviceoption relation contains ALL possible options, not those specific to the business. I have considered structuring the models as follows: …