Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn + Django + supervisor: Where are my logs?
I'm using supervisor to manage gunicorn (behind Apache) + Django. My Django LOGGING config: "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { "django.db.backends": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, # Errors logged by the SDK itself "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, 'gunicorn.error': { 'level': 'INFO', 'handlers': ['console'], 'propagate': True, }, 'gunicorn.access': { 'level': 'INFO', 'handlers': ['console'], 'propagate': False, }, }, } my gunicorn config: --preload --pid /usr/home/pids/%(program_name)s -b 127.0.0.1:8124 --access-logfile /usr/home/logs/user/access_%(program_name)s.log --access-logformat "%%({x-forwarded-for}i)s %%(l)s %%(u)s %%(t)s \"%%(r)s\" %%(s)s %%(b)s \"%%(f)s\" \"%%(a)s\"" my supervisor config: stdout_logfile=/usr/home/logs/user/%(program_name)s.stdout.log stdout_logfile_maxbytes=10MB stderr_logfile=/usr/home/logs/user/%(program_name)s.stderr.log stderr_logfile_maxbytes=10MB Somehow my access log ends up in /usr/home/logs/user/%(program_name)s.stderr.log, all other logs are and stay empty (except for Apache, which also creates an access log). Since I changed "disable_existing_loggers" from True to False, now also errors end up in that log file (before they only went to sentry). Any thoughts what is going on? When I used the same LOGGING and nginx -> apache -> mod_wsgi -> django, I did receive … -
Django Channels: Updating model field when disconnecting WebSocket in messaging
I have implemented a messaging application using Django-Channels. And inside my consumer, I get the last message of every chat when a chat message is sent. Below is my consumer __init__ method and as you can see every connection has a last_message_id def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None self.room = None self.messages_pre_connect_count = None self.last_message = None self.last_message_id = None Inside my consumer I have implemented a new_message() function such as: def new_message(self, data): author = data['from'] author_user = Profile.objects.get(username=author) message = Message.objects.create( author=author_user, content=data['message'], privatechat = self.room ) self.last_message = message self.last_message_id = message.id json_message = { 'id':message.id, 'author':message.author.username, 'content':message.content, 'timestamp':str(message.get_time_sent), 'last_message_content':self.last_message.content, 'last_message_time':self.last_message.get_time_sent() } content = { 'command':'new_message', 'message':json_message } return self.send_chat_message(content) Now I do not want to update the room last_message field every time I have a new message therefore inside my room model I have added a new function: def set_last_message(self, message_id): self.last_message = message_id self.save() This saves the last message-id of the field. However, if I call the model save() method inside the consumer disconnect() function it suddenly creates multiple instances of the room instead of editing the model field. def disconnect(self, close_code): self.room.set_last_message(self.last_mesage_id) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) Now I am not using … -
How to securely connect to Azure redis from celery-django project?
I am trying to convert from a local Redis container to a managed service in Azure. I know I have the correct server name and key because redis-cli -h <server-name>.redis.cache.windows.net -p 6379 -a <azure_key> connects. Locally my connection before in celery_manager.py was app = Celery(broker=redis://redis:6379) I updated broker successfully with the non-ssl port enabled. broker=redis://:<key>@<server-name>.redis.cache.windows.net:6379 per [this question] I tried updating the broker to: broker=redis://:<key>@<server-name>.redis.cache.windows.net:6379 I got this warning in Celery log: [2020-12-03 20:54:00,491: WARNING/celery] Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. And this exception in django-tasks: 020-12-03 20:54:31,223 - INFO - runworker - Using single-threaded worker. 2020-12-03 20:54:31,224 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2020-12-03 20:54:31,225 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive Traceback (most recent call last): File "/root/miniconda3/lib/python3.6/site-packages/redis/connection.py", line 185, in _read_from_socket raise socket.error(SERVER_CLOSED_CONNECTION_ERROR) OSError: Connection closed by server. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output … -
How to access field from ManyToMany relation on top of Foreign key relation in a django serializer?
I have the following structure: class Model_1(): model_2_ref = models.ForeignKey(to="Model_2", null=True, on_delete=models.SET_NULL) model_1_field_1 = models.CharField(max_length=120) ... class Model_2(): model_2_field_1 = models.CharField(max_length=120) model_2_field_2 = models.CharField(max_length=120) .... class Model_3(): model_2_ref = models.ManyToManyField(to="Model_2", related_name="model_2_rel_name") model_3_field_1 = models.CharField(max_length=120) .... Each record of Model_1 is related to only one record of Model_2. Also each record of the Model_2 is related to only one record of Model_3. However, a record of Model_3 can have several records in Model_2. I have a serializer for Model_1, where I would like to include it's related fields from Model_2 and Model_3. In theory, this is what I would like to achieve: class Model_1_Serializer(): model_1_field_1 = serializers.CharField() model_2_field_1 = serializers.CharField(source='model_2_ref.model_2_field_1') model_2_field_2 = serializers.CharField(source='model_2_ref.model_2_field_1') model_3_field_1 = serializers.CharField(source='model_2_ref.model_3_ref.model_3_field_1') For model_3_field_1 this syntax does not work, but for the fields of model 2 it does. How can I access the related fields of Model_3 from the serializer of Model_1? -
Django E-Commerce: cart item Iterations not pushed to db
I have the following model in my orders app: class Order(models.Model): # customer info first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) quantity = models.PositiveIntegerField(default=1) I have the following create_order view: def create_order(request): cart = Cart(request) if request.method == 'POST': form = CreateNewOrderForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() else: form = CreateNewOrderForm() PROBLEM On creating a new order, if my cart contained multiple products, I can only see 1 (the first) product in my OrderItem. Any advice on how to rectify this? -
dango delete function getting error (Field id expected a number but got)
i have create a delete function on django when try to delete a post using JQuery i get this error Field 'id' expected a number but got '\n \n \n i also add try to assign id over the pk but i get same error can anybody like to tell me how can i use this function using JQuery def ArticleDelete(request): if request.method == "POST": pk = request.POST.get('pk') article = get_object_or_404(Article, pk=pk) messages.success(request, 'The story was deleted successfully!') article.delete() return JsonResponse({"success": True}, status=200) else: return JsonResponse({"success": False}, status=400) urls.py urlpatterns = [ path('delete/', views.ArticleDelete, name='delete'), } index.js $('.delete').click(function () { var this_html = $(this); var pk = this_html.parent().parent().children().first().text(); $.ajax({ url: '{% url "del" %}', type: 'POST', headers: { "X-CSRFToken": '{{csrf_token}}' }, data: { pk: pk }, success: function () { this_html.parent().parent().remove(); } }); }) -
ManyToMany get a list of user with total aggregate for each of them
Last question, thanks to @Willem Van Onsem I'm almost done Is there any way to get a list of all user who belongs to main with an aggregate total of prix? class ReservationPay(generic.DetailView): model = Main def get_context_data(self, **kwargs): context = super(Reservation, self).get_context_data(**kwargs) context['user_rea'] = Reserveration.objects.filter(user= ?,all_resa_reservation=self.object).aggregate(total=models.Sum('prix'))['total'] class Rerservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) class Main(models.Model): all_resa = models.ManyToManyField('Rerservation',blank=True, related_name='all_resa_reservation') def total_price(self): return self.all_resa.aggregate(total=models.Sum('prix'))['total'] # get the total -
Problems with running call_command() in Django
I am trying to test the call_command to invoke migration. test_command.py: from django.core.management import call_command import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytestsite.settings') call_command('makemigrations', 'testapp') After launching I get the following error: django.core.exceptions.appregistrynotready: the translation infrastructure cannot be initializated before the apps registry is ready. Check that you don`t make non-lazy gettext calls at import time error If I understand correctly, the problem is that the registered application is not visible from the file that I run. apps.py: from django.apps import AppConfig class TestappConfig(AppConfig): name = 'testapp' Structure: mytestsite: --mytestsite: ----__init__.py ----setting.py ----urls.py ----wsgi.py --testapp: ----__init__.py ----admin.py ----apps.py ----models.py ----tests.py ----urls.py ----views.py --manage.py --test_command.py --db.sqlite3 Please tell me what could be wrong. How can the error be corrected? -
How Copy And Update A Function In Django Model
I have a BlogPost Model, and I want to define a copy function in it to copy all the posts and also all its comments. Add to that; I need to update The time of the data_created as well. Finally, It needs to return the new ID post. P.s: It would be great if show me how I can be tested in Django Console. How can I copy and How can I see the result. Thank you. from django.db import models class Author(models.Model): name = models.CharField(max_length=50) def __str__(self): return '{}'.format(self.name) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(to=Author, on_delete=models.CASCADE) data_created = models.DateTimeField(auto_now_add=True) ************ **Here I need your help.** def copy(self): for comment in self.comment_set.all(): comment.pk = None comment.blog_post.data_created = comment.blog_post.data_created.now() comment.save() class Comment(models.Model): blog_post = models.ForeignKey(to=BlogPost, on_delete=models.CASCADE) text = models.TextField() def __str__(self): return '{}'.format(self.text) -
How to prefetch or subquery a deeply nested object with condition in Django ORM
There are theses models and relations : Hours --FK--> Task --FK--> Project <--FK-- Period class Hour(models.Model): date = models.DateField(...) task = models.ForeignKey(Task, ...) class Task(models.Model): project = models.ForeignKey(Project, ...) class Project(models.Model): pass class Period(models.Model): project = models.ForeignKey(Project,...) start = models.DateField(...) end = models.DateField(...) Summary : Hour has one task Task has one project Period has one project Hour has a date Period has a start date and a end date For a given date and a given project there is one or none period possible I want to populate a period field in Hour objects the same way it would be done with prefetch_related (using queryset) I want to have something like this : hours = Hour.objects.prefetch_period().all() hours.first().period # Period(...) Using a custom queryset method like this : class HourQuerySet(models.query.QuerySet): def prefetch_related(self): return ??? For the moment I've only succeed doing this using annotate and Subquery, but I only manage to retrieve the period_id and not the prefetched period : def inject_period(self): period_qs = ( Period.objects.filter( project__tasks=OuterRef("task"), start__lte=OuterRef("date"), end__gte=OuterRef("date") ) .values("id")[:1] ) return self.annotate(period_id=Subquery(period_qs)) -
Is it possible for a react developer to completely override wagtail admin interface?
wagtail cms is reaaly awesome. But I like to create my own admin interface using next js (SSR react framework). I've searched for a way to interact with wagtail admin interface using a restful api. But I haven't found anything in documents. -
Django crispy forms is not working correctly
crispy forms doesn't work, I don't have any errors but the forms is still normal. Would like to have help on that. I don't understand I never had this probleme, thank you I have 'crispy_forms' in my INSTALLED_APPS and it correctly installed I tried many things but didn't get any result newhome.html {% load crispy_forms_tags %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'pools/newmain.css' %}"> <!-- Load an icon library to show a hamburger menu (bars) on small screens --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <div class="content-section"> <form method="POST" action=""> {% csrf_token %} {{ form|crispy }} <button class="btn btn-outline-info" type="submit">Send</button> </form> </div> {% endblock %} newmain.css body { background-color: coral; } /* Add a black background color to the top navigation */ .topnav { background-color: #333; overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #ddd; color: black; } /* … -
Display Arrow up or down in django
I have a column called kpi_delta_ind. If the column is 0 or 1,the arrow should be pointing upwards and downwards if it is <0. I am trying to use hexacode in my views.py file but it prints the code.Is there any way we can use hexacode in my views.py file or do i need to write condition in html file. Here is my Views.py file. def info(request): L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): print('&#x25B2;') elif (int(row.kpi_delta_ind) < 0): print('&#x25BC;') elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'WORKER_PORTAL' and row.kpi_key == 'WP_PAP_SUB'): L_P_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' and row.kpi_key == 'RED_INIT'): L_N_I = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' … -
Django getting NoReverseMatchexception
My root urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # new ]+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) My pages app urls.py from django.contrib import admin from django.urls import path from pages import views urlpatterns = [ path('', views.home_page, name='home_page'), path('<tab>', views.home,name='home'), ] With this, I am able to access 127.0.0.1:8000/Home 127.0.0.1:8000/About 127.0.0.1:8000/Services 127.0.0.1:8000/Portfolio All the tabs with url entry. But, when I create an url entry in html template, {% url 'About' %} getting NoReverseMatch -
Im trying to split django rows by the category Ativos like the exemple below
im getting this enter image description here but i whant this enter image description here is there a way to get this result? -
Create Login View using Django simpleJWT
I'm trying to implement a login API using JWT Authentication. I used the simpleJWT in Django. my setting.py 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),} } my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('apartments.urls')), path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view()), path('api/token/refresh/', TokenRefreshView.as_view()) ] I want to use the default user model for the login.Also the login must be done only if the user is authenticated. And I need get a POST request and to return the users credentials and the two tokens in my response body. How can I adjust my loginview accordingly? def login_view(APIrequest): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = User.objects.get(username=username) if user.check_password(password): username = user.username user = authenticate(username=username, password=password) print("Login successful") login(request, user) ``` -
Django - Exception Value: Unexpected end of expression in if tag
I can't figure out what the error could be. I have checked the docs to see if there were any syntax changes but I don't find any. Unexpected end of expression in if tag. Template error: In template /home/dhruv/django-blog/blog/templates/blog/post_detail.html, error at line 5 Unexpected end of expression in if tag. 1 : {% extends 'blog/base.html' %} 2 : 3 : {% block content %} 4 : <div class="post"> 5 : {% if post.published_date %} 6 : <div class="date"> 7 : {{ post.published_date }} 8 : </div> 9 : {% elif %} 10 : <a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}"> 11 : Publish! 12 : </a> 13 : {% endif %} 14 : 15 : {% if user.is_authenticated %} -
How to write a `localStorage` sting to a django model field
I have a string which I saved it on a kind of array in localStorage using jquery and I need to save it in a field in my form. in .js file this is the variable: $("input[name=second_step-tags]").val(array.join(', ')); # its something like A, B, C... and as I am using a wizard form, I'm trying to save write this variable into a django field which is like: {{ wizard.form.tags }} which I am putting the rendered value of template to replace the jq varibale on it as: <input name="second_step-tags" id="id_second_step-tags" cols="3" rows="3" class="textarea form-control" disabled="yes"></input> But it does not work! -
python Django REST Framework CSRF Failed: CSRF cookie not set?
I have a web-application that I need to do some API level testing. I was able to make a Django Post request API call in curl command as this: curl 'https://my-server.com/blablabla/api/public/v1/profiles' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: https://my-server.com/blablabla/api/public/v1/profiles' -H 'X-CSRFToken: ...' -H 'Connection: keep-alive' -H 'Cookie: csrftoken=...; sessionid=...' -H 'Content-Type: application/json' --data-binary '{"group":"1","name":"XYZ"}' But, if I was trying to port the similar code into python3 as follows: #!/usr/bin/python3 import requests import json TOKEN = 'X-CSRFToken: ...' COOKIE = 'Cookie: ...; sessionid=...' headers = {'X-CSRFToken': TOKEN, 'Cookie': COOKIE} post_data = '{"group":"1","name":"XYZ"}' response = requests.put("https://my-server.com/blablabla/api/public/v1/profiles", data=post_data, headers=headers) print(response.json()) print(response.ok) print(response.status_code) I have got such failure in return, {'msg': ['CSRF Failed: CSRF cookie not set.']} False 403 Does anyone know what could be wrong ? -
Why user.has_perm return false although my admin panel show me it has a permission
Hey I have a little problem with my permission in Django. In my admin panel everything seems be ok, user has all needed permission but if I try to use @permission_required decorator or has_perm test return 'false' Here is my code: models.py: ... class Comments(models.Model): photos = models.ForeignKey(UserPhotos, on_delete=models.CASCADE) comment = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) class Meta: '''Change plural name''' verbose_name_plural = 'Comments' def __str__(self): return self.comment ... views.py: ... def homeView(request): # Here is my has perm test. print(request.user.has_perm('accounts.add_comments')) #Return false. context = {} user = request.user num_visit = request.session.get('num_visits', 0) request.session['num_visits'] = num_visit + 1 if not user.is_authenticated: return redirect('instagra:login') else: context['user'] = NewUser.objects.filter(pk=user.pk) context['photos'] = UserPhotos.objects.filter(user=user.pk) context['num_visits'] = num_visit return render(request, 'main/home_view.html', context) ... -
Django admin calling the ```.save()``` method when trying to log in to the admin site
The auth user model extends AbstractUser and overrides the .save() method. The model contains two mandatory and unique fields. It also calls .full_clean() in the .save() method. The problem arises when an admin tries to log in. Django throws a validation error saying those two fields can't be blank. The error goes away when .full_clean() is commented out. Why does Django admin call the .save() method while trying to log in to the admin site? -
Django, admin TabularInLine
django admin tabularInLine is there another way to do that in admin section? people still do it this way? what is wrong here? -
Django REST app returns 502 Bad Gateway on HTTP requests containing data once hosted on GAE
I created simple Django REST app and allowed all of the hosts for CORS in my settings.py using: ALLOWED_HOSTS = ['*'] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL=True I use Postman for faking requests from client-side and one of the request I am attempting is rest-auth/registration/ request. When do a registration for locally hosted Django REST app all works fine and it responses with 200 but once I deploy it to GAE the following thing happens: If I send the empty request (that is without username, password, password_confirmation) I receive normal response that the fields are mandatory, but once I add those strings to my request the response takes long time and the outcome is 502 Bad Gateway and in my GAE logs I can only see "POST /rest-auth/registration/ HTTP/1.1" 502 [CRITICAL] WORKER TIMEOUT (pid:17) What can be the issue here? What am I doing wrong? -
How to mock API request used inside function in a Django test?
I've got a little utility function built like this to grab data from another applications API: # app/utils.py import json import requests from django.conf import settings def get_future_assignments(user_id): """gets a users future assignments list from the API Arguments: user_id {int} -- user_id for a User """ headers = { "User-Agent": "Mozilla/5.0", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", } api_app = settings.ASSIGNMENTS_API_ROOT_URL # http://project.org/appname/ api_model = "futureassignments/" api_query = "?user_id=" + str(user_id) json_response = requests.get( api_app + api_model + api_query, headers=headers, verify=False ) return json.loads(json_response.content) It basically builds the API call and returns the response data - I'd like to test this. # tests/test_utils.py import mock from unittest.mock import patch, Mock from django.test import TestCase from app.utils import get_future_assignments class UtilsTest(TestCase): def setUp(self): self.futureassignments = [ { "id": 342, "user_id": 18888, "job": 361, "location": "1234", "building": "Building One", "confirmed_at": None, "returning": None, "signature": None, }, { "id": 342, "user_id": 18888, "job": 361, "location": "1235", "building": "Building Two", "confirmed_at": None, "returning": None, "signature": None, }, ] @patch("app.utils.get_future_assignments") def test_get_future_assignments_with_multi_assignments(self, mock_gfa): """ Test for getting future assignments for a user with mocked API """ mock_gfa.return_value = Mock() # set the json response to what we're expecting mock_gfa.return_value.json.return_value = self.futureassignments assignments = get_future_assignments(18888) self.assertEqual(len(assignments), 2) … -
Django not detecting date time field in model
I have this model class Moments(models.Model): content = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.PROTECT) publishing_date = models.DateTimeField(name='Date Published', default=timezone.now) def get_publishing_date(self): return self.publishing_date Another fact is that the publishing_date is present in django admin page Now on calling the get_publishing_date, its telling that AttributeError: 'Moments' object has no attribute 'publishing_date'