Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to import and use a modified npm library packages dynamically
I am using a sigmajs library for creating node based graph visualisations. But the library package had a few bugs, so I modified a few files in the source code of the library and fixed them. I have hosted my graphs on django server, and whenever I host it, the sigma package in the package.json gets loaded dynamically each time. The static library files on my machine which I had modified and fixed bugs don't get loaded. So,I get the same old package and not the modified one. How do I access the modified library package dynamically when I host the server. -
Django - passing an object to a view through template
Is there any way to pass an object to a template and through the template pass it back to another view? Is there any technique which could do that? Reason: From my django application (MYAPP) I'm using a 3rd party django application (3APP, also maintained by me). 3APP would like to use MYAPP's Object, but I've no idea how can I pass it in this construction: MYAPP's view (MV1) is calling the 3APP's view (3V1) method, which renders the template. The template has an ajax call to another 3APPS's view (3V2) function, and this one would like to use the MYAPP's Object. (During the first pass [MV1 calls 3V1 method] it's not a problem of course, it just simply passes it through an argument, but the problem is to pass it from 3V1 to 3V2, because 3V1 renders the template, and from there an ajax call calls the 3V2) Is there any way to do this? Either pass the object to the template and from there back to the 3APP's view, or any other way? Even if there's a solution, I know it won't be too djangonic... . -
How to update ManytoManyField in UserChangeForm in Django?
I want to update user info with UserChangeForm and things go pretty well except for the ManyToManyField. When I render the page I can see that all user informations are displayed in correct order of each field like user's username will be in the username field but it's blank in manytomanyfield. #model.py class Department(models.Model): name = models.CharField(max_length=100) class CustomUser(AbstractUser): username = None email = models.EmailField(_('Email Address'), unique=True) department = models.ManyToManyField(Department) # some other fields # forms.py class EditUserForm(UserChangeForm): class Meta: model = CustomUser fields = ['email', 'department', ..] widgets = {'department': forms.CheckboxSelectMultiple()} # view.py def home(request): template_name = "app/home.html" edit_form = EditUserForm(instance=request.user) if request.method == "POST": edit_form = EditUserForm(request.POST, instance=request.user) if edit_form.is_valid(): edit_form.save() return JsonResponse({'success': True}, status=200) else: return JsonResponse({'error': edit_form.errors}, status=400) return render(request, template_name, {'edit_form': edit_form}) # template <form action="{% url 'home' %}" method="POST"> <div class="row"> {{edit_form.email}} {{edit_form.first_name}} {% for department in edit_form.department %} <h6 id="checkbox">{{department.tag}} {{department.choice_label}}</h6> {% endfor %} </div> </form> it render out the checkboxes and the names but nothing is checked inside the checkboxes. It supposed to check what i have checked when registered. -
Can i get any help to build a questionnaire/mcqs application with multiple scoring categories in django
I am a begginner in django and I have been given a project to build a questionnaire or an Mcq's web application with categorical scoring system... Did anyone can provide me the link or help related to this type of application... Thank You -
how to count anohter model django?
Hope You Are Good I Have These Models: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField() priority = models.CharField(max_length=124, choices=priority_options, default="Low") status = models.CharField(max_length=124, choices=status_options, default="In Progress") start_date = models.DateField() end_date = models.DateField() invite = models.ManyToManyField(User, related_name="invite", blank=True) def __str__(self): return self.name class Issue(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.ForeignKey(Task,on_delete=models.CASCADE) issue = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.task.name Now i Have used this Command To Count Tasks: Task.objects.filter(user=request.user,status="Completed").count() now I want to find the task which created by this user and status is completed issues how can i do that? -
python package that connect social accounts per object - django
The default behaviour of python-social-auth and other social auth package is that it bind user with a social accounts, but how can u achieve social auth per object. Here is my case. I am userX, in my django app i have a model named Company, userX managed multiple companies, and each company have their own twitter and other social accounts. So userX will add each company twitter account but after verification from twitter. Is there a way i can modify python-social-auth or all-auth package to achieve this or any other python package you can recommend. I don't want to put CharField and let user fill in the social url manually. -
In django, is it possible to have a foreign key defined to some superclass, but having returned the subclass when queried?
Assuming I have the following models: class SomeSuperClass(models.Model): ... class SomeSubClassA(SomeSuperClass) ... class SomeSubClassB(SomeSuperClass) ... class SomeConnector(models.Model): reference = models.ForeignKey(SomeSuperClass, on_delete=models.CASCADE) ... Now what I would want to have is somehow when iterating over objects of SomeConnector I always want to have right away objects of the respective subclasses, not of the superclasses. E.g. for sc in SomeConnector.objects.all(): # somehow get the correct subclass of this `reference` field here, # assuming it to be callable under sc.reference_correct_subclass: print(sc.reference_correct_subclass.__class__.__name__) could produce for example: 'SomeSubClassA' 'SomeSubClassB' 'SomeSubClassA' 'SomeSubClassA' But never should an object of the superclass be used. I know of django-model-utils and I could do something similiar by querying directly on the superclass, like this: SomeSuperClass.objects_inheritance.select_subclasses() where objects_inheritance is the InheritanceManager attached to SomeSuperClass. However I could not figure out yet how to reproduce this when the superclass is used as foreign key in another class which I want to use for querying. -
python manage.py runserver is not working but only pops up a python interpreter window
please I'm working on a django project and after creating the conda environment for the project using the anaconada shell and activated it. I opened the project up in pycharm and tried to run the server using (itachi) C:\Users\Abdul\Desktop\github\codedaddies_list>python manage.py runserver 'itachi' is my environment name but nothing happens....it shows no error codes, it only pops up the window with message Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. this is the image of the window the python pop up window please I've been stuck for days, if anyone at all can provide a solution i will be grateful thanks this is the image of my pycharm terminal where a ran the code my pycharm terminal -
How to validate one field by another in Django models?
On saving data to the model I want to validate one field by another (they are in the same model). Here is my model: class String(models.Model): key = models.CharField(max_length=60, unique=True) name = models.CharField(max_length=60) value = models.CharField(max_length=230) maxSize = models.PositiveSmallIntegerField() I want to validate value field by max size taken from field maxSize and return specific error to user when validation is failed. How to do that? -
DJANGO-increment global variable in function by every get. Request
the first code is the file that named tes.py and in this file is a function that named Program. for every url.request(second code) it proceses many things and will save to my db table. at this first code I defined id as a "increment count" global varible . I want for every get.Request in urls.py, the value of id will update by this relation: id= id+1 But its value does not change. And I dont know why even though I defined id as Global variable ! HELP PLEASE. import sqlite3 from .models import OrdersStudent ,OrdersStudent1 ,EditStudentDatasheet ,OrdersDouble , Nodecode from math import sin, cos, sqrt, atan2, radians from django.http import HttpResponse from django.shortcuts import render from django_globals import globals global j def Program(request): id = request.session.get('id') if not id: id = 1 request.session['id'] = id R = 6378.0 zz = 0 conn = sqlite3.connect("db.sqlite3") j = 0 sql = 'DELETE FROM orders_Double' cur = conn.cursor() cur.execute(sql) conn.commit() EditStudentDatasheet.objects.filter(UserId=41907).delete() EditStudentDatasheet.objects.filter(UserId=41787).delete() Nodecode.objects.filter(studentidof=41907).delete() Nodecode.objects.filter(studentidof=41787).delete() NodecodeNumberOfSubscriptions = list(Nodecode.objects.all()) Datasheet = list(EditStudentDatasheet.objects.all()) orders_student = {} orders_student={}.copy() x = Datasheet[0].Lat Dictionary1 = {} MinOfPair = 50 capacity = 3 while (MinOfPair <= 500): ThisCheck = True DoubleMergePairLAST={} DoubleMergePair = {} DoublePair={} DoubleMergePair = {} ObjectDatasheet = … -
TypeError: save() missing 1 required positional argument: 'self' : DjangoRestframework
I'm getting an error, save() missing 1 required positional argument: 'self' . I have no idea where I made mistake, it would be great if anybody could figure out the mistake, they would be much appreciated. serializers.py UserOtherInfo_obj = User( device_token = device_token, device_type = device_type, phone_number = phone_number, country_code = country_code, login_type = login_type ) UserOtherInfo_temp = User.save() temp_user1 = User.objects.filter(user=temp_user) print('temp_user1',temp_user1) UserOtherObj = temp_user1.first() -
Throttle a detail view in django rest framework
I have a custom throttle: from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' I use this throttle in a class api view as such: class PostHitCount(APIView): throttle_classes = [OncePerDayUserThrottle] def post(self, request, hitcount_pk, format=None): # my post method The url corresponding to this view is path('add-hitcount/<int:hitcount_pk>/', PostHitCount.as_view()) If i access this view for the first time via url add-count/1/, i am permitted. If i later post to the same url, i am not permitted (which is ok!). Now if i post to the url add-count/2/, the request is rejected since the user already accessed that view! How can i permit requests with another detail url? Also, is it possible to set the throttle rate to say 1/year or even 1/lifetime ? How ? -
Djangorestframwork api on production patch method not more and return rest
I am create in an api using django as backend and react as front-end using docker. in local docker all things right done ! i have tree container -django and gunicorn -pstgres -nginx django == 3.1.1 python 3.8.1 but in in vps production environment PATCH method return this error PATCH http://x.x.x.x/api/v1/product_service/product/ewrewr HTTP/1.0 400 Bad Request Date: Wed, 23 Sep 2020 10:23:41 GMT Content-Type: text/html Content-Length: 5 X-Cache: MISS from jet_appliance X-Loop-Control: 255.255.255.255 B1267694C1EE70D52467A8BA99A4D50F Connection: close reset -
Using Django "sites" framework to handle subdomains?
I am developing a language-based web application using Django. I would like to separate content using language subdomains (similar to Wikipedia, Quora, and other multilingual websites). For instance, if my website were example.com, I would like to have en.example.com for the English version of my website, es.example.com for the Spanish version of my website, and so on and so forth. I came across different Django third-party libraries that could help with subdomains but I was considering using the "sites" framework from Django itself. However, its documentation is not very explicit about subdomains but rather just talks about "websites" and it's not clear whether the framework would be suitable for my purpose. So, my question is: is the Django "sites" framework a good option for handling subdomain in a fashion similar to the one described above? -
Django FileField to upload html and send it via Email
I have a problem, I got a model with a FileField to upload an HTML template. I upload it to the MEDIA folder. I'm trying to get that template in python and send an email with it. But I have a lot of problems with the encode.  , € ... These are some of the characters i'm getting. I tried a lot of things, my actual code: template2 = default_storage.open(grupo.email.correo.path, 'r') template = template2.read() template = unidecode(template) template = Template(template) html = template.render(Context({})) email = EmailMessage( subject, html, to=[to_email] ) email.content_subtype = 'HTML' email.send(fail_silently=False) The variable grupo.email.correo is the FileField. The result: As you see, in the right of each number should be €. I tried a lot of combinations, and I get a lot of other characters, but I can't get a good decoded string, anyone knows more about this? -
Django app does not work when DEBUG_VALUE=False and using django_heroku
I tried deploying my Django website using heroku and used a library called Django-Heroku. When setting my settings.py for deployment, it returns Server Error (500) when setting DEBUG_VALUE = False, importing import django_heroku and writing django_heroku.settings(locals()) at the last line of my settings.py file. How can I check the settings set by django_heroku that disables disables my django website for production?