Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSE streaming api call more the 50 at a time in django
I have created a simple SSE streaming URL in Django(3.2.13). def index(request): def chunks(): c = 0 while True: c += 1 yield "\ndata: {}\n\n".format(c) time.sleep(1) return StreamingHttpResponse(chunks(), content_type='text/event-stream') my query is when I run this on a single tab on the browser it frequently. but when I run more than 6 tabs it does not work on the 7th tab and more, so how to create an SSE streaming URL that runs more than 50 tabs at a time. -
How to double click on the login button in test selenium
I'm testing my Django application with selenium. I would like to click on the login button twice in a row to raise the 403 error "CSRF token missing or incorrect." I tried to do it like this: btn = self.driver.find_element(By.ID, "buttonLogin") btn.click() btn.click() Not working... I also tried this : element = self.driver.find_element(By.ID, "buttonLogin") actions = ActionChains(self.driver) actions.double_click(element).perform() Do you know how I can click multiple times on the same button before the page changes ? Thanks ! -
How to exclude certain urls from django debug tool bar?
My settings.py file looks like- import os # This file contains Django settings for lower environments that use the Django Debug Toolbar. # Currently those envronments are DEV and QA. from core.settings import * # noqa: F403 # We need the ability to disable debug_toolbar for regression tests. DEBUG = os.getenv('DEBUG_MODE', 'FALSE').upper() == 'TRUE' def toolbar_callback(request): return DEBUG DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": toolbar_callback, } INSTALLED_APPS += ['debug_toolbar', ] # noqa: F405 MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] # noqa: F405 I want to exclude certain pages from loading debug toolbar. The reason being that the pages have a lot of SQL and debug toolbar is taking too long to load and hence page results in a timeout -
why can't import django in vscode
Help me please figure out what this is about, it shows that Django is not found `from django.urls import path urlpatterns = [ path('', views.index, name='index') ]` -
Django admin application works 100% for superuser but for staff users with full permissions some apps don't appear for users
My Django admin application works 100% for superuser but for staff users with full permissions some apps like GARAGE don't appear for users even though it has full permissions! How can I debug or where can I be blocking this access in my code? I don't use decorator or proxy! I don't use custom template! I don't have has_perm or has_module_perms in my code Permissions user all users permissions actived Admin Site Django Admin dont show App #settings.py INSTALLED_APPS = [ 'garagem.apps.GaragemConfig', 'ckeditor', 'covid', 'documento', 'agenda.apps.AgendaConfig', 'mailer', 'ouvidoria.apps.OuvidoriaConfig', 'licitacao.apps.LicitacaoConfig', 'demanda.apps.DemandaConfig', 'compras.apps.ComprasConfig', 'procedimento.apps.ProcedimentoConfig', 'solicitacao.apps.SolicitacaoConfig', 'endereco.apps.EnderecoConfig', 'servidor.apps.ServidorConfig', 'parametros.apps.ParametrosConfig', 'comunicacao.apps.ComunicacaoConfig', 'receita.apps.ReceitaConfig', 'artigo.apps.ArtigoConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'core', 'rest_framework', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) #urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView from . import views from django.views.generic import TemplateView # <-- from django.contrib.auth import views as auth_views import debug_toolbar from rest_framework.schemas import get_schema_view from rest_framework import routers from servidor.api import viewsets as servidorsiewset route = routers.DefaultRouter() route.register(r'servidorapi', servidorsiewset.ServidorViewSet ,basename='servidorapi') favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True) urlpatterns = [ path('garagem/', … -
serializer import error in django rest-framework
#serializers.py from rest_framework import serializers class CommunitysStaffSerializer(serializers.ModelSerializer): role = serializers.CharField(max_length=100,default='management') community = serializers.PrimaryKeyRelatedField(read_only=True) user = serializers.PrimaryKeyRelatedField(read_only=True) #views.py from rest_framework.response import Response from admindashboard.serializers import CommunitysStaffSerializer @api_view(['POST']) def Communitystaff(request,pk=None): if request.method == 'POST': serializer = CommunitysStaffSerializer(data = request.data) if serializer.is_valid(): Staff = CommunityStaff.objects.get(id = request.data['id']) Staff.community=serializer.validated_data['community'] Staff.role=serializer.validated_data['role'] Staff.save() return Response({'detail': 'entry successfully'}) else: return Response({'error': 'unable to entry staff'}, status=status.HTTP_400_BAD_REQUEST) else: return Response (serializer.data) #error File "C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\urls.py", line 2, in from admindashboard.views import Login_post,City_post,City_list,City_update,City_remove,Community_update,Community_list,Community_post,Community_detail,Admindash_list,Admindash_update,Admindash_remove,Admindash_post,Admindash_detail,Communitystaff File "C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\views.py", line 11, in from admindashboard.serializers import CommunitysStaffSerializer ImportError: cannot import name 'CommunitysStaffSerializer' from 'admindashboard.serializers' (C:\Users\Pinakee.Somyadarshee\Desktop\mykommunity\admindashboard\serializers.py) -
Django socketio history
I am trying to do a chat app in django with socketio. I tried to do it from this video. I did it but how can I add history to the chat with consume the least space in my computer? With history I mean even for example if I refresh the page or close the computer If I go again I will see the same conversation. But I don't want the messages consume much space in my computer. -
django pagination duplicate posts
Hello i got a wierd error pagnation works fine on my home.html but in my categories.html it duplicate post as soon as it paginates how can i fix this. Here is code to the files that the problem is in. problem should be from the def CategoryView. i tried to change the order_by id and some small stuff in the categories but cant understand why post duplicates on pagnation. views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator def LikeView(request, pk): post = get_object_or_404(Post, id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() ordering = ['-post_date'] paginate_by = 3 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, … -
Django Q Error: could not translate host name "db" to address: Temporary failure in name resolution
This is the docker compose production configuration that I have created: version: '3' services: db: image: postgres:12.8-alpine restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db ports: - 5400:5432 redis: image: redis:alpine ports: - 6379:6379 web: build: context: . dockerfile: Dockerfile volumes: - .:/ps_survey - static_volume:/ps_survey/staticfiles env_file: - ./.env.prod depends_on: - redis - db django-q: build: . command: python manage.py qcluster volumes: - .:/ps_survey env_file: - ./.env.prod depends_on: - redis nginx: build: ./nginx volumes: - static_volume:/ps_survey/staticfiles ports: - 86:80 depends_on: - web volumes: postgres_data: static_volume: Dockerfile configuration: FROM python:3 WORKDIR ./ps_survey ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./req2.txt . RUN pip install -r req2.txt COPY . . CMD gunicorn ps_survey.wsgi:application --bind 0.0.0.0:8000 .env.prod configurations DEBUG=0 SECRET_KEY='******************************' DJANGO_ALLOWED_HOSTS=["*"] DB_NAME=********* DB_USER=********* DB_PASSWORD=******** DB_HOST='db' DB_PORT=5432 EMAIL_HOST_PASSWORD=********** EMAIL_HOST_USER=********** EMAIL=************* PASSWORD=********** BACKGROUND=True .env.prod.db configurations POSTGRES_USER=******* POSTGRES_PASSWORD=****** POSTGRES_DB=******* Error that I am getting : django-q_1 | 16:00:19 [Q] ERROR could not translate host name "db" to address: Temporary failure in name resolution Because of which, the task is not running -
Running Django + Postgresql + Gunicorn in Docker container using compose - file permission errors
I am using Docker-desktop version version 20.10.16 on Ubuntu 20.0.4 LTS I want to Dockerise Django (v3.2), PostgreSQl (v14.3) and Gunicorn (v20.1.0) in a single container. And use those containers as Virtual hosts being serviced by a single Nginx instance that is running on my local machine. I am able to build images, and a container, but setting up the django application fails, because of a file error in creating/writing to myporoj.log I am currently, not using nginx as a proxy server to the virtual hosts - I want o resolve this isse first before moving on to using Nginx with my setup. Here are additional relevant details: My file structure (on local machine), is as follows: /path/to/myprojectweb/ /myproj /myproj settings.py wsgi.py # etc. Dockerfile.prod compose.prod.yml Dockerfile.prod.yml # Builder Image FROM python:3.8-slim-buster as Builder WORKDIR /usr/src/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWEITEBYTECODE 1 RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev RUN pip install --upgrade pip pipenv COPY Pipfile* ./ RUN pipenv lock --keep-outdated --requirements > requirements.txt \ && pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt # Final Image FROM python:3.8-slim-buster RUN mkdir -p /home/app /var/log/gunicorn # create user + group app that apps will run as. … -
How to get Select Option Value in Views Django
This is my HTML form template <form action="" method="post"> {% csrf_token %} <div class="d-flex form-inputs"> <select class="form-select" aria-label=".form-select-lg"> <option selected>Spanish To English</option> <option selected>English To Spanish</option> <option value="1">French To English</option> </select> <input name="txt" class="form-control p-3" type="text" placeholder="Search..."> <a href="#"><img src="/static/assets/image/search.png" alt=""></a> </div> </form> I want to get User selected value from Select Option to views. This is views function def lang_convert_view(request): if request.method == "POST" and 'txt' in request.POST: txt = request.POST.get('txt') data = custom_function_name(txt) context = {'data': data} else: context = {} return render(request, 'index.html', context) Anyone, please help me -
How do I format Django form CharFields to be next to each other one the same line?
Currently, I'm using a the Django Form class to create a form. I'm trying to make it so that all of the CharField fields have their own row, except for a few specific one's that I would like to share a row. These are the CharFields I currently have: class ExampleForm(forms.Form): example_1 = forms.CharField(max_length=20, required=False) example_2 = forms.CharField(max_length=20, required=False) example_3= forms.CharField(max_length=20, required=False) def __init__(self, *args, **kwargs): super(MetadataForm, self).__init__(*args, **kwargs) self.fields['example_1'].widget.attrs['style'] = 'width:15%;' self.fields['example_2'].widget.attrs['style'] = 'width:15%;' self.fields['example_3'].widget.attrs['style'] = 'width:15%;' Here is how they're rendered in the HTML: <label for="id_example_1">Example 1:</label> <input type="text" name="example_1" maxlength="20" style="width:15%;" id="id_example_1"> <label for="id_example_2">Example 2:</label> <input type="text" name="example_2" maxlength="20" style="width:15%;" id="id_example_2"> <label for="id_example_3">Example 3:</label> <input type="text" name="example_3" maxlength="20" style="width:15%;" id="id_example_3"> In an attempt to format example_1 and example_2 on the same line, I tried floating the labels to the left and then adding space between them by increasing the margin: #example_1, #example_2, #example_3 { float: left; margin-left: 100px; } However, while this formats the boxes very oddly: It also doesn't do anything for the labels. I'm not sure how to reference the labels since they don't have id values I can use. If there's a way that I can have example 2 and 3 formatted on the … -
How to make queries to remote Postgres in different views in Django?
I'm making a project where I need to access to remote databases and get data from it. I'm connecting to remote postgres database and getting list of all tables in my class-based view like so: try: # connect to the PostgreSQL serve conn = psycopg2.connect( host='host', database='db_name', user='username', password='password', port='port', ) # create a cursor cursor = conn.cursor() cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") rows = cursor.fetchall() # close the communication with the PostgreSQL cursor.close() except (Exception, psycopg2.DatabaseError) as error: print(error) Now, in another view I want to make other queries (like retrieving specific rows from specific table). How am I able to do that? The goal is to take all credentials from user's input in template to connect to db. Then on another template choose which table and which rows to use to get certain data. -
Django Update view doesn't update an object during test
I'm writing tests for my views and I'm stuck with the UpdateView and the POST request. For this simple test I try just to change first_name but assertion fails. What am I doing wrong? However, when I call the response.context it gives me that: [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7f070ed6eee0>>, 'request': <WSGIRequest: POST '/employees/7/update'>, 'user': <SimpleLazyObject: <User: testuser@test.com>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7f070ecb33d0>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f070ed1b130>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Employee: John Smith>, 'employee': <Employee: John Smith>, 'form': <EmployeeUpdateForm bound=True, valid=False, fields=(first_name;last_name;user;position;reports_to;birthday;hire_date;address;phone_number;pfp)>, 'view': <employees.views.EmployeesUpdateView object at 0x7f070ed1b310>}] The test: class TestEmployeesUpdateView(TestCase): def setUp(self): self.test_user = User.objects.create_user( username='test_user', email= 'testuser@test.com', password='Testing12345') self.test_employee = Employee.objects.create( first_name='Bob', last_name='Smith', user=self.test_user, position='SM', birthday=date(year=1995, month=3, day=20), hire_date=date(year=2019, month=2, day=15), address='...', ) self.client = Client() def test_updateview_post(self): self.client.force_login(user=self.test_user) response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'frist_name': 'John'}) self.test_employee.refresh_from_db() self.assertEqual(self.test_employee.first_name, 'John') The view: class EmployeesUpdateView(LoginRequiredMixin, UpdateView): model = Employee template_name = 'employees/employee_details.html' form_class = EmployeeUpdateForm And the error: FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post self.assertEqual(self.test_employee.first_name, 'John') AssertionError: 'Bob' != 'John' - Bob + John -
Exclude auto-generated files by Django within pre-commit-config.yaml using REGEX
Since the auto-generated Django files don't fulfill numerous pylint-requirements, my pre-commit checker fails: The files look usually like so: They seem to be located automatically in a sub-folder called "migrations": Now, I tried to leverage the pre-commit exclude expressions with a proper REGEX. This one seemed to work on an online REGEX-tester: [\w-]+\d+[^\\]*.py Here is the proof: Now, putting this into my pylint pre-commit checker does unfortunately nothing: I also tried to just exclude the "migrations" folder, but I could not find a working expression either. How can I make this work? -
Status: Select a valid choice. 1 is not one of the available choices Django 3
Here i am using Django 3.0 and Python 3.7. When i am trying to update the user phone number or email id i am getting this issue. Here is my views.py: class ClientUserInfoUpdate(CustomAdminMixin, UpdateView): model = ClientUser template_name = "core/user_info_mutiple_edit_form.django.html" form_class = ClientUserInfoUpdateForm user = None methods = None def get_success_url(self): return reverse("admin_user_update", args=[self.user.pk]) def get_form_kwargs(self): kwargs = super(ClientUserInfoUpdate, self).get_form_kwargs() self.user = kwargs['instance'] self.methods = self.user.get_userinfodata() kwargs['user'] = self.user kwargs['methods'] = self.methods return kwargs def get_context_data(self, **kwargs): context = super(ClientUserInfoUpdate, self).get_context_data(**kwargs) context['user'] = self.user context['methods'] = self.methods context['countries'] = countries_sorted for method in ContactInfoMethod.objects.all(): context['types_' + method.name.lower()] = ContactInfoMethodType.objects.types_by(method.name) return context Here is my forms.py: class ClientUserInfoUpdateForm(forms.ModelForm): user = None methods = None # sort of a copy of fieldsets, but utilising the dynamic capabiliities of the form #formsections = [] new_info = [] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.methods = kwargs.pop('methods') super(ClientUserInfoUpdateForm, self).__init__(*args, **kwargs) #self.formsections = [] # auto generate the form based upon self.methods (!!!) for dm in self.methods: methodtypes = ContactInfoMethodType.objects.types_by(dm['method'].name) methodtypes_choices = methodtypes.values_list('pk', 'type__name') if(dm['method'].use_dialling_code): dialling_code_choices = countries_sorted_with_dial_choices i = 1 methodname = "" for info in dm['items']: fn = info.dynamic_form_field_name() self.fields[fn] = forms.CharField() if(dm['method'].name.lower() == "email"): self.fields[fn] = forms.EmailField() self.fields[fn].name = fn self.fields[fn].verbose_name … -
Why doesn't it return the messages?
I'm trying to retrieve all messages in the chat, the messages are saved in the ChatMessage template. The insertion of a new message does not create problems for me, the recovery yes, in the send_message() function I use the send() with the correct data. {'command': 'messages', 'messages': [{'id': 204, 'author': 'C12VC08213@are.it', 'content': 'Ciao da tutti', 'timestamp': '2022-06-06 13:57:37.103215'}, {'id': 236, 'author': 'CCCVC08213@are.com', 'content': 'Ciao da tutti quanti', 'timestamp': '2022-06-07 07:59:50.818133'}, {'id': 269, 'author': 'C11VC0@are.it', 'content': 'Ciao da tutti quanti1', 'timestamp': '2022-06-07 08:51:58.980090'}]} I don't understand why it doesn't send it, the websocket restiusce nulls me or it doesn't respond. from concurrent.futures import thread from django.contrib.auth import get_user_model # from asgiref.sync import await from asgiref.sync import async_to_sync, sync_to_async from channels.db import database_sync_to_async import json from chat.models import ChatMessage, ChatRoom from users.models import Operator from chat.utils import ( get_chatmessages, get_operator_info, # get_current_chatroom, # get_operator, ) from channels.generic.websocket import AsyncWebsocketConsumer from chat.api.v1.serializers import ChatMessageSerialiser, ChatRoomSerializer class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): print("------------------ receive") text_data_json = json.loads(text_data) if text_data_json["command"] == "fetch_messages": await self.fetch_messages(data=text_data_json) # self.send(text_data=fetch['messages']) # await self.channel_layer.group_send( # self.room_group_name, # {"type": "chat_message", "message": messages}, # ) if text_data_json["command"] == "new_message": message = text_data_json["message"] await self.new_message(data=text_data_json) self.send(text_data=message) await self.channel_layer.group_send( self.room_group_name, {"type": "chat_message", "message": message}, … -
serializer error for list field when i run tests in Django
I have a weird problem when using TestCase and Client in Django. from django.test import TestCase, Client data is: data = { "match_status": MatchStatus.FINISHED, "winner_side": Side.CITY, "end_time": get_now(), "players": [ { "uuid": self.player.uuid, "role": self.role, "success_acts": [self.act1.id], "failed_acts": [self.act2.id, self.act3.id] } ] } from django.test import Clien as client self.client.post(reverse("match-finish", args=[self.match_create.uuid]), data=data) this is a custom serializer: class MatchFinishPlayerSerializer(BaseSerializer): uuid = UUIDField() role = IntegerField() success_acts = ListField() failed_acts = ListField() class MatchFinishSerializer(BaseSerializer): match_status = IntegerField() winner_side = IntegerField() end_time = DateTimeField() players = MatchFinishPlayerSerializer(many=True) Part of view.py: @action(methods=["POST"], url_path="finish", url_name="finish", detail=True) def finish(self, request, uuid: UUID = None): serializer = self.get_serializer_class()(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.validated_data) and when I run python manage.py test I got an error: {'players': ['This field is required.']} -
How to use default logger and custom logger in django but avoid duplicate logs
I have two sets of APIs in a Django project that I want to use my custom logger. So in every viewset I will be doing logger.info(...) or logger.error(...) before the responses. Everywhere else in the project, like Admin pages and other tools, I'd like to leave the logging as it is for now. This is how I have defined my LOGGING in settings.py. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': 'ts=%(asctime)s level=%(levelname)s caller=%(filename)s:%(funcName)s:%(lineno)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } The problem is that the way it is, the logging in the APIs is duplicated for every request, my logger and the existing django logger. How can I "disable" the default django logger in the APIs but keep it everywhere else? -
Testing a django `post_save` signal that includes function calls that occur after db transaction is committed
When django tests are running, database transactions are not committed. How do I test an event triggered by object creation but that happens after the db transaction has been committed? I have a Campaign model and the below post_save signal. Using Django TestCase it is difficult to assert that the functions within transaction.on_commit are called in the case when a new Campaign object is created. When the signal runs in the test context, it always thinks that an existing campaign object is being edited, not that one has been newly created. Therefore I cannot test the else branch of the if statement. How could I test the case when Campaign.objects.filter(pk=instance.pk).exists() is False? Signal: @receiver(post_save, sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting") def create_handwriting(sender, instance, **kwargs): """Whenever a campaign is created or updated, trigger the handwriting cloud function to (re)generate the handwriting image. """ if Campaign.objects.filter(pk=instance.pk).exists(): transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-edited", stage="campaign") ) transaction.on_commit(lambda: delete_campaign_pages(campaign_pk=instance.pk)) else: transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-created", stage="campaign") ) transaction.on_commit(lambda: enqueue_handwriting_generation(campaign_pk=instance.pk)) Test: class TestSignals(TestCase): def setUp(self): self.factory = RequestFactory() @mock.patch("lettergun.apps.writing.signals.log_campaign_progress") @mock.patch("lettergun.apps.writing.signals.enqueue_handwriting_generation") @mock.patch("lettergun.apps.writing.signals.delete_campaign_pages") def test_create_handwriting_edit_existing_campaign( self, delete_campaign_pages, enqueue_handwriting_generation, log_campaign_progress ): # disconnected in the factory so we need to reconnect it here signals.post_save.connect( sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting", receiver=create_handwriting, ) enqueue_handwriting_generation.return_value = True log_campaign_progress.return_value = True with self.captureOnCommitCallbacks(execute=True) … -
Share Django authentication for FastAPI
I have working Django project. Now i want to add FastAPI so at existing django templates i can make API requests to refresh data without reloading whole template (like tables for example). The question is how to connect FastAPI to existing django authentication system, so it can use sessions from db, so that user authenticate only once, when logging in to django project. Here some options i have investigated: Change django base authentication to oauth2, also set fastapi to oauth2 (though i desire to configure fastapi, not changing django) Fetch django sessions from db on each api request and verify user Both django and fastapi on the same server and can share the same db. Maybe some better options are possible. Please advice what would be the best approach to use django already authenticated user data with fastapi? Thx -
How to import images ImageField from excel, using Django import_export?
I am using django-import-export, Excel file as file.xlsx when importing an ImageField the image is saved as a link "C:\Users\hp\Desktop\images\gallery\29.jpg" and not an actual image into database. models.py class Product(models.Model): name = models.CharField( max_length=200, verbose_name='Nom') slug = models.SlugField( max_length=150, unique= True, verbose_name='URL') reference = models.CharField( max_length=200, verbose_name='Référence', unique=True, blank=True, null=True) def __str__(self): return self.name class PhotoProduct(models.Model): image = models.ImageField(upload_to='images/produits') actif = models.BooleanField(verbose_name='actif', default=True) product = models.ForeignKey(Product, related_name="photos", on_delete=models.CASCADE) def __str__(self): return str(self.product) ########### ressources.py class PhotoProductAdminResource(resources.ModelResource): product = fields.Field(column_name='product', attribute='product', widget=ForeignKeyWidget(Product, field='id')) class Meta: model = PhotoProduct fields = ( 'id', 'product', 'actif', 'image', ) ########### admin.py @admin.register(PhotoProduct) class PhotoProductAdmin(ImportExportModelAdmin): list_display = ('id', 'product', 'actif') list_display_links = ('id','product', ) list_editable = [ 'actif'] resource_class = PhotoProductAdminResource form = PhotoProductModelForm -
Why in DJANGO the Templates are not updated when I refresh the page with new data in the DB?
The problem is that when I change data through a form or by the django admin if it is saved in the database, but when redirecting to another view or refreshing the screen with f5 it does not show the changes in the user views unless I start session again or delete the cookies, something that for each change you have to perform this operation, however in the django admin views if everything is updated normally with a simple f5. This is very rare since the page has been working for more than 1 year without this problem and suddenly this happened. I'm using: Stevedore Nginx gunicorn 20.0.4 Django 3.1.4 python 3.9 sqlite 3 and bootstrap 4.6 for user views I thought it was just the update of my browser but in any browser the same thing happens I did not find a similar problem in any forum, I hope you can help me or give me an indication of what is causing this -
modelize schema procede withdjango
Is it possible to draw a dynamic schema procede with django ? i tried to draw shapes with #svg in HTML/CSS but it is a static solution ... And I need to do dynamic modification in the schema , hypertext for exemple Any help please ? -
Manytomay field is None or can't call field in a view in django
I have a problem in my code,I'm Trying to querying to my course model, I have a many to may field of course in user model,now I need to query to course model that course title or id is equal to user's courses My course model is: class Courses(models.Model): title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) active = models.BooleanField(default=False) default_course = models.BooleanField(default=False) My user model in another app is: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) courses = models.ManyToManyField('academy.Courses', related_name='user_courses', blank=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_author = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_adviser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) I have to say my user model and course model are in different app This is my view: class CoursesListView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = UserSerializer def get_queryset(self, **kwargs): user = self.request.user course = Courses.objects.filter(title__in=user.courses.title) I tried so many code but none of them worked,please any one can help me how can I write this view? as I said I want to call courses that have same id or title with user courses