Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
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 = …