Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.2 post_save signal invoked for all model instances even if 1 instance is used in the code to save
Is post_save signal called for all the mailbox model instances when we click save button in django model admin? Does the post_save signal work continuously in Apache server?When it is executed behind Apache, just when we refresh the page it again saving the same password in next password column as the previous password column.I need to check password history for 5 passwords to not repeat.The post_save code: def check_oldest_password_instance(mbox): passwd_list = [] oldest_password = None oldest_password_datetime = datetime.now() pfield = '1' n = 0 mphistory = Phistory.objects.filter(mbox=mbox) if mphistory: print('======phistory exists====', mphistory) for p in mphistory: if p.password1: passwd_list.append(p.password1) oldest_password_datetime = p.datetime1 oldest_password = p.password1 pfield = '1' if p.password2: passwd_list.append(p.password2) if oldest_password_datetime > p.datetime2: oldest_password_datetime = p.datetime2 oldest_password = p.password2 pfield = '2' if p.password3: passwd_list.append(p.password3) if oldest_password_datetime > p.datetime3: oldest_password_datetime = p.datetime3 oldest_password = p.password3 pfield = '3' if p.password4: passwd_list.append(p.password4) if oldest_password_datetime > p.datetime4: oldest_password_datetime = p.datetime4 oldest_password = p.password4 pfield = '4' if p.password5: passwd_list.append(p.password5) if oldest_password_datetime > p.datetime5: oldest_password_datetime = p.datetime5 oldest_password = p.password5 pfield = '5' print(len(passwd_list),pfield,'passwd_list_len,pfield_oldest') n = len(passwd_list) # For new mailbox, check if all 5 values are populated # if n == 0: # pfield = '1' if n == 1: … -
want to remove the extra space from the values while searching in the django admin
I have a list and as the text is too long i have applied the line breaks in it using the code as below: and also showing an example for the text TESTTRACK00000000000 000000008 def track(self, obj): if obj.tracking_no: line_length = 20 # used to break the text when it reaches 20 characters lines = [obj.tracking_no[i:i+line_length] + '\n' for i in range(0, len(obj.tracking_no), line_length)] return ''.join(lines) return obj.tracking_no but when copying the text for applying search in it there is a space coming in between like TESTTRACK00000000000 000000008 when copying the text for searching i want it as TESTTRACK00000000000000000008 . need to remove the extra space in it. I tried using strip() but its not working -
Create Django admin panel where project is created using another language
I have created a project using Golang. I have used PostgreSQL as the database. Now I want to make an admin panel for this project using Django. I want directly reflect the database tables in the Django admin panel. As I am not running the project under the Django server and I don't have any apps and models, how can I show them in the admin panel? -
How to set different permissions for GET and POST methods with ListCreateAPIView?
I would like to set IsAuthenticated permission for GET and IsTeamLeader permission for POST with ListCreateAPIView and ModelSerializer, but without having a unique permission that check the request method in has_permission, as suggested in these questions here and here. How could I do that ? @permission_classes([IsAuthenticated]) class ManagerListView(ListCreateAPIView): queryset = Manager.objects.all() serializer_class = ManagerSerializer class IsTeamLeader(permissions.BasePermission): def has_permission(self, request, view): if Manager.objects.filter(pk=request.user.pk).exists(): return Manager.objects.get(pk=request.user.pk).is_team_leader class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) fields = serializers.JSONField(write_only=True) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) return user class Meta: model = Manager fields = ('id', 'email', 'first_name', 'last_name', 'username', 'role', 'is_team_leader', 'password1', 'password2', 'fields') read_only_fields = ('id', 'first_name', 'last_name', 'role', 'is_team_leader', 'address', 'contact') -
How do I run a function in the background of my Django server and send the output to the correct view?
I have a queue of users defined as: class QueueItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) In addition, I have the following functions to interact with the queue: def should_pair(user1, user2): # Add user preferences later # compare the attributes of the two users and return True if they should be paired, False otherwise if user1.school == user2.school: return True return False def pair_users(): # get all users in the queue users = QueueItem.objects.all() # pair users two at a time for i in range(0, len(users), 2): user1 = users[i] try: user2 = users[i + 1] except IndexError: return None if should_pair(user1, user2): return [user1, user2] return None My question is, is there a way that I can run the pair users function constantly in the background, and when it finds a match, send a common url for the 2 users to a view that can redirect the users to the common link? This is for a video chat app that connects random users (similiar to Omegle). -
how can i override django-rest-auth registration serializer?
I'm using dj-rest-auth (https://dj-rest-auth.readthedocs.io/en/latest/) and trying to implement a custom registration form. in login, i want: username password email(i want to remove it) in signup username email ( i want to remove it) password password2 When I am trying to register a new user I get this error: enter image description here My registration Serializerenter image description here My User model enter image description here -
Docker Container Running But it thorgh the error Teplate does not Exist
Hi I'm New In Docker I Have Created A Django Application Its Running in Local machine Good But When I try To run In docker Container its Run Properly But When I sent Request The Found The Error Template Does Not Exist Dockerfile #syntax=docker/dockerfile:1 #FROM ubuntu:latest FROM ubuntu:latest FROM python:3.8-slim-buster WORKDIR /app #COPY requirements.txt requirements.txt #RUN pip3 install -r requirements.txt # #CMD python . /manage.py runserver 0.0.0.0:8000""" # pull the official base image # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update&& \ apt-get -y install sudo RUN apt-get install -y tesseract-ocr RUN apt-get install -y build-essential libpoppler-cpp-dev pkg-config python-dev mupdf RUN apt-get install ffmpeg libsm6 libxext6 -y RUN apt-get install -y default-jre RUN apt-get install -y default-jdk RUN apt-get update RUN apt-get install -y python3-pip RUN pip3 install --upgrade pip #RUN pip3 install virtualenv #RUN python3 -m virtualenv env #RUN source env/bin/activate COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt # copy project COPY . /app EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] # My Docker File Look Like that docker-cpmpose.yml version: "3" services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Folder Structure Directory: … -
Can't Manually Assign Django ModelForm Variables for some reason
I'm can't figure out why it won't set my author field. I'm calling form.author = request.user but it won't set for some reason. It keeps setting to Null Does anybody happen to know what I'm doing wrong? .models class PoopMascot(models.Model): name = models.CharField(max_length=128) image = models.ImageField(upload_to='upload/mascots/') votes = models.ManyToManyField(User, related_name='votes', blank=True) author = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True ) .forms class PoopMascotForm(forms.ModelForm): class Meta: model = PoopMascot fields = ['name', 'image', 'author'] field_classes = { 'class': 'form-control'} widgets = {'author': forms.HiddenInput()} helper = FormHelper() .views def mascot(request): form = PoopMascotForm() user = request.user anonymous_pooper = User.objects.get(username="Anonymous_Pooper") if request.method == 'POST': form = PoopMascotForm(request.POST, request.FILES) form.author = request.user if user.is_authenticated: form.author = user else: form.author = anonymous_pooper if form.is_valid(): print('entering form is valid') form.save() -
Django Query which join two models and find the average of scores
In my model there is some Tests in Tests model, each test have some questions in it which are in Question model , and some types are relate to each test which are in TestTypes model , and there is a QuestionResult model which save the scores of each test: These are the models : Test : class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 types = models.ManyToManyField( 'TestType', related_name='tests', ) questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) def __str__(self): return self.title Question: class Question(BaseModel): question_text = models.TextField() def __str__(self): return truncatewords(self.question_text, 7) TestResult : class TestResult(BaseModel): candidate = models.ForeignKey( 'Candidate', on_delete=models.CASCADE, related_name='test_results', ) test = models.ForeignKey( 'exam.Test', on_delete=models.CASCADE, ) test_score = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f'{self.candidate.user.email} - {self.test.title}' TestType : class TestType(BaseModel): title = models.CharField(max_length=255) def __str__(self): return self.title now i want to get the score which each type earned for example test1 got score =90 and test1 has two types : HTML and C++ . Test2 got score = 50 and test2 has two types : HTML and Python now i want to find the score which HTML … -
Log out via GET requests is deprecated and will be removed in Django 5.0
I get this warning while running tests with selenium and pytest. Here's the test method: def test_registration( self, driver, live_server, valid_user_data, django_user_model ): selenium_signup(driver, live_server, valid_user_data, django_user_model) selenium_sign_in(driver, live_server, valid_user_data) page_source = driver.page_source.lower() assert 'sign in' not in page_source assert 'sign up' not in page_source assert 'sign out' in page_source driver.find_element(By.ID, 'btnGroupDrop1').click() driver.find_element(By.XPATH, '//*[contains(text(), "Sign out")]').click() assert 'sign in' in page_source assert 'sign up' in page_source This is where the warning is generated: driver.find_element(By.XPATH, '//*[contains(text(), "Sign out")]').click() Here's the button: <li><a class="dropdown-item" href={% url 'signout' %}>Sign out</a></li> The view uses django LogoutView and here's how it's defined from django.contrib.auth.views import LogoutView urlpatterns = [ path('signout/', LogoutView.as_view(), name='signout'), ... ] What would be a clean way to fix this? -
Is it necessary add IsAuthenticated permissions to permission_classes in view that is inherited from LoginRequiredMixin
I have a class-based view called ProfileDetail. It is inherit LoginRequiredMixin from django.contrib.auth.mixins. And then set permission_classes = (IsAuthenticated,). Basically all client that view ProfileDetail is already logged-in, hence authenticated. My question is, is it necessary to set permission_classes = (IsAuthenticated,) even though all client already logged-in? What's your advice? Thank you. -
dj-rest-auth How to authenticate user with REST_USE_JWT = True when testing
I have Django Rest Framework site that use dj-rest-auth as authentication. I enable REST_USE_JWT = True in my settings.py. I want to test some API that require rest_framework.permissions.IsAuthenticated. I create client with rest_framework.test.APIClient() in my test. I try to login and view some API, but i got HTTP_401_UNAUTHORIZED. I try to login with post username, email, and password to dj-rest-auth login url, and got response access_token, refresh_token, etc. Then use credentials() to include it in header. But the client still got HTTP_401_UNAUTHORIZED. I don't know if i am doing it right. Please help me to authenticate the client in test. Thanks in advance! class ProfileTests(APITestCase): @classmethod def setUpTestData(cls): cls.username = "test" cls.email = "test@test.com" cls.password = "test" cls.user = get_user_model().objects.create_user( username=cls.username, email=cls.email, password=cls.password, ) cls.authenticated_client = APIClient() response = cls.authenticated_client.post( reverse("rest_login"), { "username": cls.username, "email": cls.email, "password": cls.password, }, format="json" ) cls.authenticated_client.credentials(HTTP_AUTHORIZATION=settings.JWT_AUTH_COOKIE + " " + response.data["access_token"]) -
Figuras interactivas HTML CSS JS DJANGO
Pará un proyecto de Django con HTML CSS y JS me piden poner una figura de un cuerpo humano en la que se puedan seleccionar articulaciones haciéndoles click y se marque un checkbox que tenga encima la articulación. Es decir, tiene que haber un checkbox posicionado encima de cada articulación y se tiene que poder intersctuar independientemente con cada uno. Alguna ayuda? Gracias! La única solución que se me ocurrió es posicionar la imagen del cuerpo fija y posicionar (también fijo) cada checkbox, pero me parece un laburo muy pesado y creo que debería haber alguna otra forma. -
Django 'runserver' displays blank page. It returns the source code and shows no errors. This problem was not here the last time I opened VS Code
I am doing a CS50 Web Project and it worked just fine until today. Now when I run the command 'python3 manage.py runserver (any port I want)' it displays: Just a blank page Django shows no errors, the settings are fine. the '/admin' page functions without issues and the page source code is shown without issues. This is not a Jinja syntax problem as well, as I checked it was correct to. It shows this blank screen no matter the URL I go too. If I open a live server it 'works' in that it displays contents to me. For example: Using this comand: Live server VS command It displays at least something close to the page: 'Live' display. !!! - I got also {% endblock %} at the end. I tried: Opening it with Live server, it displays contents, however, obviously, not what I need. Chaning the settings, they are fine. Chaning the port, that's not the issue. Checking the Jinja syntax, that's not the issue. Restarting VS code, no change (the last time, once again, had no issues regarding such problems). What is interesting is that if I remove all the code from a template like 'index.html': If … -
Internal Server Error 500 -- EC2, django, nginx, uwsgi
I'm developing and deploying django based web-app through EC2 with nginx and uwsgi. Because of developing Front-side (based on react), I send several http request to my server's public IPv4. And the first few moment, my request is normally answered by server. All data is safely delivered to "http://localhost:3000". But in some reason, after rebooting my EC2 instance, my nginx returned "500 (Internal Server Error)". More detailed information is descripted below. [log] /var/nginx/access.log --> any further information than internal server error 3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env.local HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.production HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.staging HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /live/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, … -
Reverse for 'add_vacation' with no arguments not found. 1 pattern(s) tried: ['ferias/adicionar/(?P<id_client>[0-9]+)/\\Z']
Boa noite pessoal, Espero que vocês consigam salvar este mero estudante. Estou desenvolvendo um sistema pro meu TCC e vou testar ele no quartel onde trabalho. É um sistema de lançamentos de saídas e retornos de férias, viagens, etc. Estou fazendo com Python + Django, porém está dando o seguinte erro depois que faço o log in no sistema. urls from django.urls import path, re_path from . import views app_name = 'holidays' urlpatterns = [ path('', views.list_vacations, name='list_vacations'), path('administrador-ferias/<int:id_client>', views.list_vacations_admin, name='list_vacations_admin'), path('adicionar/<int:id_client>/', views.add_vacation, name='add_vacation'), path('excluir/<int:id_client>/', views.delete_vacation, name='delete_vacation'), path('editar/<int:id_holidays>/', views.edit_vacation, name='edit_vacation'), path('editar-administrador/<int:id_holidays>/', views.edit_vacation_admin, name='edit_vacation_admin'), ] view # está função é reponsável pela adição das férias, dispensas, etc. @login_required(login_url='/contas/login/') def add_vacation(request, id_client): template_name = 'holidays/add_vacation.html' context = {} if request.method == 'POST': form = HolidaysForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.clients = Client.objects.get(id=id_client) f.user = request.user f.save() form.save_m2m() return redirect('holidays:list_vacations') form = HolidaysForm() context['form'] = form return render(request, template_name, context) template {% if user.is_authenticated%} <li class="nav-item"> <a class="nav-link" href="{% url 'clients:list_militar' %}">Cadastro pessoal</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'holidays:add_vacation' %}">Realizar Lançamentos</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'holidays:list_vacations' %}">Histórico de lançamentos</a></li> {% endif %} Não sei se o erro poderia ser causado do import de Client dentro da view Holidays. Eu … -
TypeError: PaystackPayment() missing 1 positional argument: "request"
I'm getting the error PaystackPayment() missing 1 required positional argument: 'request' at line 246 of my core.views of my Ecommerce project when trying to access the function PaystackPayment(). I don't know what is wrong. views: def PaystackPayment(request): try: order = Order.objects.get(user=request.user, ordered=False) secret_key = settings.PAYSTACK_SECRET_KEY ref = create_ref_code() amount = int(order.get_total() * 100) client_credentials = request.user.email paystack_call = TransactionResource( secret_key, ref) response = paystack_call.initialize( amount, client_credentials ) authorization_url = response['data']['authorization_url'] # create payment payment = PaystackPayment() payment.user = request.user payment.ref = ref payment.email = client_credentials payment.amount = int(order.get_total()) payment.save() # assign the payment to the order order.ordered = True order.email = client_credentials order.ref_code = ref order.paystack_payment = payment.amount order.save() # send confirmation order email to the user subject = f'New Order Made by {request.user.username} today totaled {int(order.get_total())} ' message = 'Hello there ' + \ ', Thanks for your order. Your order has been received and it is being processed as we shall get back to you shortly. Thank you once again!' email_from = settings.EMAIL_HOST_USER recipient_list = [request.user.email, ] send_mail(subject, message, email_from, recipient_list) messages.success(request, 'Your order was successful') return redirect(authorization_url) except ObjectDoesNotExist: messages.info( request, """ Their was an error when you where possibly entering the checkout or payment fields. You … -
Facebook comment section for multiple pages
I am trying to add a Facebook comments section on each page in my website. For example, pk=27 (https://www.donadogs.org/en/dogs/27/) should have its own section and pk=28 a different one. https://developers.facebook.com/docs/plugins/comments#configurator allows me to create a section per URL provided. This means that I can't add a section for each separate PK on my website as each URL has to be provided manually. Is there a workaround to this? -
Redirect with data in Django
I have a user authorization through a link: def ClientAuth(request, link_code): try: code = Links.objects.filter(code=link_code).values('code', 'status') if code[0]['status']: username, password = 'Client', '**************' client = authenticate(request, username=username, password=password) if client is not None: login(request, client) return redirect('clientPage') return HttpResponse("Hello its work") else: return render(request, 'client/404.html') except: return render(request,'client/404.html') If the link exists in the database and the active one authorizes us as a client and redirects it to his page, it looks like this in urls: urlpatterns = [ path('clientPage/',views.clientPage, name = 'clientPage'), path('<link_code>/', views.ClientAuth, name='ClienAuth') ] My task is that, depending on the link the client used to log in on the client page, he receives different information, for example, the link ID Is there any way I can pass this data from the ClientAuth function when redirecting? redirect to this page: def clientPage(request): print(request) return HttpResponse("Hello") -
Django's DRF has_object_permission method not called with get_object
I scratch my head to understand why the has_object_permission bellow has no effect, because the documentation says that this method should be executed with get_object. What could be the reason ? @permission_classes([HasViewObjectPermission]) class IndividualDetailsView(RetrieveAPIView): serializer_class = IndividualSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) return Individual.objects.get(pk=pk) class HasViewObjectPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): return False -
How can I Show Only my Videos in Django-Rest-Framework?
I'm using Django and React to create YouTube clone. And I have an admin panel where user can delete and edit his videos. But the problem is that it showing my videos and other users videos. How can make that the admin panel will show only my videos? views.py Api Views class AdminVideoDetail(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] quesryset = Video.objects.all() serializer_class = VideoSerializer videos.js Videos in the admin panel import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import Link from '@material-ui/core/Link'; import Paper from '@material-ui/core/Paper'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import DeleteForeverIcon from '@material-ui/icons/DeleteForever'; import EditIcon from '@material-ui/icons/Edit'; import Button from '@material-ui/core/Button'; const useStyles = makeStyles((theme) => ({ cardMedia: { paddingTop: '56.25%', // 16:9 }, link: { margin: theme.spacing(1, 1.5), }, cardHeader: { backgroundColor: theme.palette.type === 'light' ? theme.palette.grey[200] : theme.palette.grey[700], }, videoTitle: { fontSize: '16px', textAlign: 'left', }, videoText: { display: 'flex', justifyContent: 'left', alignItems: 'baseline', fontSize: '12px', textAlign: 'left', marginBottom: theme.spacing(2), }, })); const Videos = (props) => { const { videos } = props; const classes = useStyles(); if (!videos || videos.length === … -
Why is my Pillow Image not being considered a File when I try to save it into my django image field?
I'm writing a Form Creation/Filling out forms app, and I'm to the point where I'm taking canvas data from the front-end and filled out fields of text input and draw them on a picture of the form with the pillow library. The problem is when I try to save the data for the form I get this error from "serializer.error" from django-rest-framework: "'FilledForm': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}" Here is the Api view: @api_view(['POST']) def postForm(request): dataDict = request.data FieldCoords = {} # Define Formtype selectedForm = dataDict["SelectedForm"] del dataDict["SelectedForm"] # Get Datalist for form creation datalist = list(FormData.objects.filter(FormType=selectedForm).values()) #Set Signature Images on Form and Fill form with inputs for field in datalist: #Get Field Positions of Model if field["FieldType"] == "SignatureField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"]) elif field["FieldType"] == "TextField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"],abs(field["height"])) elif field["FieldType"] == "DateField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"]) #print(FieldCoords) #Place Signature Fields On FormImage sigFields = json.loads(dataDict["Signatures"]) FormImage = Image.open(f"{MEDIA_ROOT}/{selectedForm}") del dataDict["Signatures"] for field in sigFields: datauri = sigFields[field] uri = datauri.split("base64,") sNameselect = field.split(" - ") bytes = base64.b64decode(uri[1]) img = Image.open(io.BytesIO(bytes)) for keyCoordSet in FieldCoords: print(keyCoordSet) print("Name" + sNameselect[0]) if sNameselect[0] == keyCoordSet: print("Im here") FormImage.paste(img, FieldCoords[keyCoordSet], … -
How to test Django API that uses Celery task with send_email?
So, in my Django project, I have an API view that sends data by email to the user. That job doing by Cerely (celery task). I want to test that API sends the right data. But I can't realize how to do that with that celery job, because the user created in a testcase has a non-exist email. So even if I run celery worker in a test it'll fail due to the wrong email with SMTP error... If we implement the view without celery we can use Django mail.outbox[0].body to inspect the mail. But with Celery we can't. Pls, advise. -
Django Rest Framework - nested serializer is not working like expected or how the docs explains
I have a post model and i have a post image model. I would like to show the images related to a post in the API, but I cannot seem to get it right.I only see the post data and not the related images. Here are my post and post image models: class Post(models.Model): EV = "Everybody" FO = "Followers" FR = "Friends" AUDIENCE = [ (EV, "Everybody"), (FO, "Followers"), (FR, "Friends"), ] category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=user_directory_path, null=True, blank=True) can_view = models.CharField(max_length=10, choices=AUDIENCE, default=EV) can_comment = models.CharField(max_length=10, choices=AUDIENCE, default=EV) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post") image = models.FileField( upload_to=post_directory_path, default="posts/default.png", null=True ) class Meta: db_table = "post_images" ordering = ["post"] def image_tag(self): return mark_safe( '<img src="/storage/%s" width="50" height="50" />' % (self.image) ) image_tag.short_description = "Image" This is the post and post images serializers: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ["id", "image", "post"] extra_kwargs … -
How to use two loop correctly in python
Hi guys I have problem This is my code : services = { 'first':[], 'second':[] } x = [1,2,3,4,5] for i in services: print('loop-one - ',i) for i in x: services['first'].append(i) print(services) Output of this code is {'first': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5], 'second': []} If you notice He added twice . my purpose is something like this , I want add once {'first': [1, 2, 3, 4, 5], 'second': []} Thanks !