Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use function TruncDay(or another one like TruncMonth) to sum results from two or more models?
for example I'm using this query to get counts by month: Item1.objects .annotate(month=TruncMonth('timestamp')) .values('month') .annotate(c=Count('id')) .values('month', 'c') now to every month I want to sum every month of the second model (Item2) Item2.objects .annotate(month=TruncMonth('timestamp')) .values('month') .annotate(c=Count('id')) .values('month', 'c') Can i do this with the ORM instead programatically? i know that i can iterate the results and sum if the month match, but i don't want to do that. -
Django model based on an SQL table-valued function using MyModel.objects.raw()
If it's relevant I'm using Django with Django Rest Framework, django-mssql-backend and pyodbc I am building some read only models of a legacy database using fairly complex queries and Django's MyModel.objects.raw() functionality. Initially I was executing the query as a Select query which was working well, however I received a request to try and do the same thing but with a table-valued function from within the database. Executing this: MyModel.objects.raw(select * from dbo.f_mytablefunction) Gives the error: Invalid object name 'myapp_mymodel'. Looking deeper into the local variables at time of error it looks like this SQL is generated: 'SELECT [myapp_mymodel].[Field1], ' '[myapp_mymodel].[Field2] FROM ' '[myapp_mymodel] WHERE ' '[myapp_mymodel].[Field1] = %s' The model itself is mapped properly to the query as executing the equivalent: MyModel.objects.raw(select * from dbo.mytable) Returns data as expected, and dbo.f_mytablefunction is defined as: CREATE FUNCTION dbo.f_mytablefunction ( @param1 = NULL etc etc ) RETURNS TABLE AS RETURN ( SELECT field1, field2 etc etc FROM dbo.mytable ) If anyone has any explanation as to why these two modes of operation are treated substantially differently then I would be very pleased to find out. -
Django forms - create a form for each object in model, and then save to the corresponding PK
I'm new to django (and programming in general). Sorry if I used the wrong vocabulary (and please correct me). This is what i'm trying to do: I have this model: Class A(models.Model): name = models.CharField(max_length=100, null=True, default='John') first_number = models.FloatField(blank=True, default=1) second_number = models.FloatField(blank=True, default=2) third_number = models.FloatField(blank=True, default=3) And I have this form: class Numbers(ModelForm): class Meta: model = A fields = ['first_number', 'second_number'] In my template, I created a for for x in a (given that 'a' is A.objects.all()): {% for x in a %} {{form}} {% endfor %} When I submit the form, though, I cant get the corresponding numbers. I only saves the last number I enter in both 'first_number' and 'second_number' for the both objects that I created. How can I save the correct values? -
Automatically configuring settings to local or production depending on the IP address
I have 4 settings files - __init__.py (which controls the other 3 files) base.py (which has settings needed when running the site locally or in production mode) local2.py (which has settings needed for running the site locally) production.py (which has settings needed for running the site in production) In __init__.py I want to identify the ip address which would then dictate if we need to use local2.py or producction.py. My problem is a lot of the ways I know to capture ip address only work with request. Which from what I gather is something you pass to views. Therefore these methods do not work in my settings __init__.py file. Does anyone know a way of capturing the ip address via the setting file? I looked at Django: Get remote IP address inside settings.py but it did not help me. -
Django calculate models total field
I want to return rate, but got this error in admin unsupported operand type(s) for +: 'NoneType' and 'NoneType' class SomeModel(models.Model): code_style_rate = models.DecimalField(max_digits=4, decimal_places=2) decision_rate = models.DecimalField(max_digits=4, decimal_places=2) severity_rate = models.DecimalField(max_digits=4, decimal_places=2) @property def rate(self): return (self.code_style_rate + self.decision_rate + self.severity_rate) / 3 def __str__(self): return self.rate -
Django server returning HTML instead of JSON when using fetch()
I'm trying to fetch data from an API in my own Django server but for some reason, it is returning HTML instead of a JSON object Here's the API route Im tring to fetch from: path("emails/<str:mailbox>", views.mailbox, name="mailbox") Here's the mailbox function in views.py: @login_required def mailbox(request, mailbox): # Filter emails returned based on mailbox if mailbox == "inbox": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=False ) elif mailbox == "sent": emails = Email.objects.filter( user=request.user, sender=request.user ) elif mailbox == "archive": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=True ) else: return JsonResponse({"error": "Invalid mailbox."}, status=400) # Return emails in reverse chronologial order emails = emails.order_by("-timestamp").all() return JsonResponse([email.serialize() for email in emails], safe=False) Here's the model i'm trying to fetch from: class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "read": self.read, "archived": self.archived } Here's the JS code: if(document.querySelector('h3').innerHTML === 'Inbox'){ fetch('/emails/inbox') .then(response => response.json()) .then(emails => { console.log(emails); }); Finally, here's my console output no … -
How to serialize foreignkey in Django Rest Framwork?
I have jobs model and categories model and they have one to many relationship. so I want to get the details of category as well when i pull the job model. Abstract Job Model class JobAbstractModel(models.Model): title = models.CharField(max_length=150) no_of_vacancy = models.PositiveIntegerField() offered_salary = models.CharField(max_length=200) deadline = models.DateTimeField() education_level = models.CharField(max_length=200) description = models.TextField(blank=True) description_points = models.TextField(blank=True) skills = models.TextField() other_specification = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') is_active = models.BooleanField(default=1) class Meta: abstract = True Job Model class Job(JobAbstractModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='categories') job_level = models.CharField(max_length=50, choices=JOB_LEVEL_CHOICES, default='Mid') employment_type = models.CharField(max_length=50, choices=EMPLOYEMENT_TYPE_CHOICES, default='Full') experienced_required = models.FloatField() created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='jobs_created_by') def __str__(self): return self.title Category Model class Category(models.Model): name = models.CharField(max_length=150) is_active = models.BooleanField(default=1) image = models.ImageField(upload_to='categories_images/') def __str__(self): return self.id + ":"+self.name Serializers.py class CategorySerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField() class Meta: model = Category fields = "__all__" def get_image(self, category): request = self.context.get('request') image_url = category.image.url return request.build_absolute_uri(image_url) class JobOverViewSerializer(serializers.ModelSerializer): #category = serializers.CharField(source='category.name', read_only=True) categories = CategorySerializer(read_only=True, many=True) class Meta: model = Job fields = ['id', 'no_of_vacancy', 'employment_type', 'experienced_required', 'categories'] jobs.py class JobCategoriesView(APIView): def get(self, request): categories = Category.objects.all() serializer = CategorySerializer(categories, many=True, context={'request': request}) return Response(serializer.data) class JobOverView(APIView): def get(self, … -
Django separate settings and .env files (python-decouple): the specified path was not found for static files
I have developed a Django Project and try to manage different configuration (dev and prod) and .env using python-decouple. Below my project architecture and different config files. Maybe I misunderstand but in my comprehension : I have differents settings.py files (dev and prod) that inherit from my "base" settings.py Some variables must be kept secret: these variable are store in .env files that will not be share (.gitignore) In production, these secret variables are read from .env in settings files I run python manage.py migrate --settings=core.settings.dev python manage.py runserver --settings=core.settings.dev and got an error FileNotFoundError: [WinError 3] The specified path was not found: 'D:\Users\xx\DevSpace\PROJECT_FOLDER\core\static' That right because static folder is at the same level as core app. But how to configure this path? - PROJECT_FOLDER |_ core |_ wsqi.py |_ settings |_ __init__.py |_ .env |_ base.py |_ dev.py |_ prod.py |_ manage.py |_ static |_ css |_ images |_ db.sqlite3 .env SECRET_KEY=rqps9azjw7i0@_(qxirwr!@0w3f)$prsky9l7bt8t-(y)_tiuj base.py from decouple import config STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), os.path.join(BASE_DIR,'randomization/static'), os.path.join(BASE_DIR,'unblind/static'), os.path.join(BASE_DIR,'pharmacy/static'), ) dev.py from .base import * SECRET_KEY = 'f!hap7sff#f@8$1iix@(%d4f=88swwetxkhbq=%^x)ga2eowbs' DEBUG = True prod.py from .base import * SECRET_KEY = config("SECRET_KEY", default="unsafe-secret-key") DEBUG = False -
Static CSS not being applied to django-allauth templates
My templates do not seem to be able to access static css files. The project using all-auth for authentication. My file structure is as follow: Project Folder App 1 App 2 Static CSS style.css Templates Account login.html signup.html base.html home.html base.html is as follow: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Shuffle</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='{% static "css/style.css" %}' rel="stylesheet"> </head> <body> <div id="card"> {% block content %} {% endblock %} </div> <!--card --> </body> </html> The rest of the templates extend from base.html. On inspecting the rendered page, all the html are correct but the styling is missing. Please help! :) -
Multiple nginx instances = gateway time-out; each instance works fine if addressed directly
This was working yesterday, but I made some changes which I have now reverted, and now it seems to be broken, and I can't find out why. I desperately need some tips on how to debug this. Background I've made multiple applications that move around quite a bit. In each app's repository, I've included nginx and docker configurations for two scenarios: Running as the only application on a server, and running alongside other applications. Because I want each repository to be "complete", I don't want any of the applications to assume whether or not they will be served by a "main" nginx instance in front. They should be capable of running using their "default", "standalone" configuration, and of existing alongside any number of other applications that also listen on the same ports, etc. Of course, running multiple web servers or APIs, for example, alongside one another would cause port allocation conflicts (and other problems), so there is some manual setup involved when running multiple apps on the same server. Almost all these applications consist of a Django REST framework server, a postgres database and an nginx reverse proxy. I made a separate repository with template files and instructions for running … -
Django custom auth model
Not sure how to name this problem, let me elaborate. I have very old django project, been migrating it since django 1.5 or so. It has always had class Member, extending User and has been practically used as authentication model for the app. AUTH_USER_MODEL was never changed, however SOCIAL_AUTH_USER_MODEL is set to custom auth model (and it works that way). Currently I am migrating to django 3.x and I am ran into trouble with django-registration - it used to work with Member set as model, but now it checks it against AUTH_USER_MODEL. Bottom line is, I want to make it the "right" way and set proper custom model and make sure I do it right before I dig deep into it as I expect it not to be too easy. When I simply set AUTH_USER_MODEL to custom model, I get error members.Member.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. When I make Member extend AbstractUser instead of User, I am missing id and fields as django then expects all data in single table (rather than having 2 one-to-one relationship tables). I could somehow manually merge data into this single table, but I am … -
Django REST API update view returns http 405
I'm trying to build a single page app (Vue) with a django backend. It's a very simple app to practice Vue + Django Rest Framework. The app allows the user to creating, delete and view (list) stories (just a title, datetime and content (simply text)) and this works fine. I'm now trying to also implement editing capabilities, but I get an error with regards to CORS headers. My backend code is very simple. Settings.py # relevant parts of settings.py INSTALLED_APPS = [ ..., 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", ] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) urls.py: urlpatterns = [ path('', views.StoryList.as_view(), name='stories'), path('<int:pk>/', views.StoryDetail.as_view(), name='story'), path('delete/<int:pk>/', views.StoryDetail.as_view(), name='delete_story'), path('update/<int:pk>/', views.StoryDetail.as_view(), name='update_story') ] views.py: from django.shortcuts import render from django.http import HttpResponse, Http404 from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Story from .serializers import StorySerializer class StoryList(APIView): def get(self, request, format=None): stories = Story.objects.all() serializer = StorySerializer(stories, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = StorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) class StoryDetail(APIView): def get_object(self, pk): try: return Story.objects.get(pk=pk) except Story.DoesNotExist: … -
Django: substitute unique_together with UniqueConstraint
I am trying to enforce a constraint upon a Vote model in my Django application, namely that a user cannot vote more than once the same object. To do so I am using unique_together: class Vote(models.Model): vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_votes") definition = models.ForeignKey(Definition, on_delete=models.CASCADE, related_name="definition_votes") class Meta: # Ensure user cannot vote more than once. unique_together = ["user", "definition"] This works, I think. However, in Django's documentation for unique_together it is noted that UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future. How can I substitute the above code using unique_together with code using UniqueConstraint? -
Validate Unique email django rest framework serializer
I have a model where Email field is unique. I thought it would make every email lowercase as it has normalize_email() method on User instance. However, it normalizes domain part only so Company@gmail.com is considered to be unique if company@gmail.com exists. So I decided to create validate_email() in my serializer to always return a lowercase email. It is a field validation and it is described in docs. def validate_email(self, value): return value.lower() However, looks like this method returns the value after the serializer has checked if the value exists in the database. Here is an example: if I try to create a user with user@gmail.com and it already exists, it will return "user already exists" which is expected. However, if I run with User@gmail.com it will run a SQL request first and check User@gmail.com != user@gmail.com and after that it'll try to create a new instance with user@gmail.com because it is returned from validate_email() and IntegrityError will be raised because it becomes user@gmail.com which is already in DB! I could do something like def validate_email(self, value): norm_email = value.lower() if User.objects.filter(email=norm_email).exists(): raise serializers.ValidationError("Not unique email") return norm_email but this is another request to DB and I don't want it. So … -
Django F expression seems to be case-insensitive with TextField on mariadb
Suppose I have the following model definition: class ExampleModel(models.Model): a = models.TextField(blank=True, null=False) b = models.TextField(blank=True, null=False) Django's F expression seems to lower text from b field when I want all objects where value from field a equals value from field b to be excluded from the queryset. ExampleModel.objects.create(a='sentence', b='Sentence') # should be 1 since 'sentence' != 'Sentence' assert ExampleModel.objects.exclude(a=F('b')).count() == 0 # 'Sentece' is what should be under F('b') but apparently it is not assert ExampleModel.objects.exclude(a='Sentence').count() == 1 I'm using mariadb with Django 2.1.15 What is the cause of this behaviour? -
get report of all tasks done on every week of day
Hi I have a model like : class Task(models.Model): todo_list = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=1024, blank=True) completion_date_time = models.DateTimeField(blank=True, null=True) now I want to get that on every week day how much task were completed . Like on {'Monday':2, 'tuesday':3 , 'Wednesday':2, 'Thrusday':1, 'Friday':2, 'Saturday':0, 'Sunday':0} -
How to add Django model method to serializer without explicit defining the fields?
model class Doctor(models.Model): ...tons of fields def no_of_ratings(self): ratings = Rating.objects.filter(doctor=self) return len(ratings) serializer class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('__all__') # this will NOT show method fields = ('id', 'first_name', 'no_of_ratings') # this works I don't think this is a duplicate of this as my question explicit mentions model methods. -
Django: unsure how to access this jinja variable because of '@' in dictionary key
The output shows the url tag of the enclosure containing a file that needs to be retrieved is '@url' instead of the usual 'url'. Can't use '{{item.enclosure.url}}' nor '{{item.enclosure.@url}}' How can I retrieve this url as a Jinja variable? Reading RSS feed with Jinja The output of the HTML with Jinja -
Creating war file of django project?
I have created a sample Django project and want to convert a Django project into a war file. I have followed the step given in https://pythonhosted.org/django-jython/war-deployment.html creating .war of Django project but got an error in the manage.py file. Please help me to create a war file of the Django project. -
How do I link to my model to its foreign key and manytomany fields in the templates in django?
I am new to django and have a rather basic question, however I have not been able to find my answer online, so apologies if this has been answered previously... I have 3 models: class Type(models.Model): name = models.CharField(max_length=100) class Exercise(models.Model): name = models.CharField(max_length=100) type = models.ForeignKey(Type, on_delete=models.CASCADE, default=1) class Area(models.Model): name = models.CharField(max_length=100) notes = models.TextField(blank=True, null=True) exercise = models.ManyToManyField(Exercise) and 3 views: class AreaView(ListView): model = Area template_name = 'workouts/areas.html' context_object_name = 'areas' def get_context_data(self, **kwargs): context = super(AreaView, self).get_context_data(**kwargs) return context class ExerciseView(ListView): model = Area template_name = 'workouts/exercises.html' context_object_name = 'exercises' def get_context_data(self, **kwargs): context = super(ExerciseView, self).get_context_data(**kwargs) return context class TypeView(ListView): model = Exercise template_name = 'workouts/types.html' context_object_name = 'types' def get_context_data(self, **kwargs): context = super(TypeView, self).get_context_data(**kwargs) return context I have registered each view to a url like this: urlpatterns = [ path('', AreaView.as_view(), name='areas'), path('exercises/<int:id>', ExerciseView.as_view(), name='exercises'), path('types/<int:id>', TypeView.as_view(), name='types'), ] and created 3 templates, areas.html: {% for area in areas %} <ul> <li><a href="{% url 'exercises' id=area.id %}">{{ area.name }}</a></li> </ul> {% endfor %} exercises.html: {% for area in areas %} <ul> <li><a href="{% url 'types' id=exercise.id %}">{% for exercise in area.exercise.all %}{{ exercise }}{% endfor %}</a></li> </ul> {% endfor %} and types.html: … -
django 3.1 of the fifth part of the document unit test failure [closed]
我是一个正在学习django的小白 正学到官方文档 3.1 的第五部分的单元测试,发现单元测试无法运行,结果永远是 Ran 0 tests in 0.000s 项目的settings也设置了 INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] tests.py 的文件都是复制官方文档的 import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_da is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) -
Pass python list into json
I have a list in python (Django) that I'd like to pass as a json response. But when I console log the data out I get an empty array called num. numbers = [10,15,20] def get_data(request, *args,**kwargs): data = { 'num': numbers, } return JsonResponse(data) -
python manage.py runserver command not working and below is th error
Error: Traceback (most recent call last): File "/Users/syedwaseem/python1/myenv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/Users/syedwaseem/python1/myenv/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module -
what to if i made changes to production.env google gives timeout error when i load my website
I turn debug=true and add 27.0.0 to allowed host list in production.env and run the python manage.py runserver command to connect to the local host. I worked fine. But later when change the debug to false and try to reach my site on google it gives time out error. What should i do to get my site up run in google or production server? -
Importing Data from a JSON to django AttributeError: 'WSGIRequest' object has no attribute 'data'
I am trying to make an E-commerce website from the tutorial series- Django Ecommerce Website | Add to Cart Functionality | Part 3 in django freamwork. My views.py is: def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print('productId: ', productId) print('action: ', action) return JsonResponse('Item was added', safe=False) My js file is: var updateBtns = document.getElementsByClassName('update-cart') console.log('updateBtns length:', updateBtns.length); for(var i=0; i<updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('product ID: ', productId, "Action: ", action) console.log('User: ', user) if (user == 'AnonymousUser'){ console.log('user is not authnticated'); } else{ updateUserOrder(productId, action); } }) } function updateUserOrder(productId, action){ console.log('user is authenticatred, sending data') var url = '/update_item/' fetch(url,{ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data: ', data) }) } Here my problem is after adding those line in updateItem function in views.py the error is shown in the console- data = json.loads(request.data) AttributeError: 'WSGIRequest' object has no attribute 'data' How can I solve this problem? Actually I do not know about rest API or json clearly.