Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django assign a task to many users
I want to create a task for many users(students) but I want every student to have his own "copy" of this task so students can't edit each other's tasks. E.g.: I, as a teacher, creates a task and assign 4 students to that task. Every student get exactly the same task and can change it's progress etc. Does anyone has any idea how to achieve that? I've stucked. Thanks in advance. models.py class Task(Timestamp): STATUSES = ( ("new", "new"), ("in-progress", "in-progress"), ("done", "done") ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() status = models.CharField(choices=STATUSES, max_length=50, default="new") students = models.ManyToManyField(CustomUser, related_name='students') def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Task fields = [ 'id', 'owner', 'created_at', 'updated_at', 'title', 'description', 'status', 'attachments', 'students' ] -
Understanding order_by of multi-valued fields (Django)
Having read the django docs on order_by there is a note/warning that (if I have understood correctly) says that: If you are ordering a queryset using a multi-valued field, then every element in that queryset that has multiple related items, will be added multiple times to the resulting queryset created by order_by. I tried testing this out with a basic example: Minimal Reproducible Example class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField('Topping', through='PizzaToppings') class PizzaToppings(models.Model): pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE, related_name="pizza_toppings") topping = models.ForeignKey('Topping', on_delete=models.CASCADE, related_name="pizzas_with_topping") amount = models.IntegerField() class Meta: ordering = ["amount",] class Topping(models.Model): ingredient = models.CharField(max_length=100) then >>> p1 = Pizza.objects.create(name="Cheese and Tomato") >>> p2 = Pizza.objects.create(name="Pepperoni") >>> cheese = Topping.objects.create(ingredient="Cheese") >>> tomato = Topping.objects.create(ingredient="Tomato puree") >>> p1.toppings.add(cheese, through_defaults={"amount":4}) >>> p1.toppings.add(tomato, through_defaults={"amount":3}) >>> p2.toppings.add(cheese, through_defaults={"amount":2}) >>> p2.toppings.add(tomato, through_defaults={"amount":1}) So far, so normal. But this is where things get confusing: >>> q1 = Topping.objects.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q2 = p1.toppings.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q1.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>, <Topping: Topping object (2)>, <Topping: Topping object (1)>]> >>> q2.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>]> The problem As … -
ModuleNotFoundError: No module named 'crud.core' in python 3 and windows 10
Researched a bit and haven't found any solution whatsoever. My application name is CRUD. Whenever I try to run my application using the: python manage.py runserver I get the following error: ModuleNotFoundError: No module named 'crud.core' I used the following commands: python -m venv crud pip install django pip install djangorestframework python manage.py startapp rental And the file that's causing trouble (api.py): from rest_framework import routers from .core import views as myapp_views router = routers.DefaultRouter() router.register(r'friends', myapp_views.FriendViewset) router.register(r'belongings', myapp_views.BelongingViewset) router.register(r'borrowings', myapp_views.BorrowedViewset) I'm on windows and running python 3.9.0 -
How to determine Django version of a given code?
I have a site in Django. How to know (by watching at code), which version of Django it requires and which Python it requires? -
How to access individual form objects from a modelformset_factory?
I've deployed a formset using modelformset_factory. However rather than saving the entire formset, I need to loop through the forms in the formset, perform some logic on them, and save each one individually. At the moment I'm having to use the ID from each form in the formset to get the object it represents. Is there a cleaner way of doing this? def accounts_import(request,pk): account = get_object_or_404(Account, pk=pk) # Create transactions queryset for use in formset transactions = Transaction.objects.filter(account=account.monzo_account, import_type=None).order_by('-id') FormSet = modelformset_factory(Transaction, form=TransactionsImportForm, extra=0) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): for form in formset: object = Transaction.objects.get(id=form.cleaned_data['id']) # Do some stuff on the object object.save() -
How make users own their data in django
Currently, if you’re logged in, you’ll be able to see all the products, no matter which user you’re logged in as.how can i show merchants only the products that belongs to them. i try this views.py def users_homepage(request): product=Product.objects.filter(merchant=request.user).order_by('date_added') and i get this error " Cannot query "mustapha": Must be "Merchant" instance" my models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Product(models.Model): merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) -
Django Rest Framework Custom Permission does not recognize user
I am trying to enforce a custom permission in DRF. Specifically, I am trying to see whether a user is authorized to access an object. I adapted this solution from another post here but it does not quite work for me. The permission class always assumes that request.user is an Anonymous user. What am I missing? permissions.py class CanSeeWishlist(permissions.BasePermission): def has_permission(self, request, view): try: wishlist = Wishlist.objects.get( pk=view.kwargs['pk']) except: return False if wishlist.private: print(request.user) # Prints Anonymous User if request.user.id == wishlist.owner.id or request.user.id in wishlist.members.all(): return True return False return True api.py class WishlistViewset(viewsets.ModelViewSet): serializer_class = WishlistSerializer queryset = Wishlist.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] def get_permissions(self): if self.request.method == 'GET': self.permission_classes = (CanSeeWishlist,) return super(WishlistViewset, self).get_permissions() -
I had written some css code but it is not appearing on my server
This is my css file This is html file where i loaded the css file -
I have tried python manage.py makemigrations and end up with this error
from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/home/khurshid/Documents/git/uzedi2/lib/python3.8/site-packages/django/db/models/fields/init.py) -
Generate authtoken through consumer or middleware in Django
I have searched quite a lot, can't find anything regarding the authtoken generation using Django Channels, and how to return it. As routes are protected through the use of TokenAuthMiddlewareStack() like specified here i can't just create a consumer with a specific route to the consumer itself So, what are my options? Ask for the client to generate the token via http request Send user's password and username once through json request (Over a TLS connection) and if TokenAuthMiddlewareStack can't find an authorization header, it'll look for the username and password fields in order to generate and return a token Option number one makes things bureaucratic. Option number 2 is more a band-aid solution. Is there a more practical solution? Thank you. -
How do I attribute different color for each of the django model choices
Following is my models.py: class Table(models.Model): choices = ( ("BUY", "Buy"), ("HOLD", "Hold"), ("SELL", "Sell"), ) remarks = models.CharField(max_length=200, choices=choices, default="HOLD", null=True) Is there some way to attribute different color for each of the choices? For instance, if i choose "BUY" it is displayed in a color, say blue, on my html page. Thanks! -
Issue with inheriting from the django-graphene default GraphQLView
I have the need to do the following: path( '<uuid:uuid>/graphql', csrf_exempt( viewsets.MyCustomGraphQLView.as_view() ) ), That is, to pass in a uuid which can reference a different graphql schema dynamically. I'm attempting to do something like the following: from django.views.generic import View from django.shortcuts import get_object_or_404 from graphql.type.schema import GraphQLSchema from graphene_django.views import GraphQLView class MyCustomGraphQLView( GraphQLView ): def __init__( self, *args, **kwargs ): super(MyCustomGraphQLView, self).__init__(*args, **kwargs) self.schema = self.get_object().get_schema() assert isinstance( self.schema, GraphQLSchema ), "A Schema is required to be provided to GraphQLView." def get_queryset(self, *args, **kwargs): return MyObject.objects.all() def get_object(self, *args, **kwargs): print(self.uuid) // None print(MyObject.objects.get(uuid=self.uuid)) // None queryset = self.get_queryset() obj = get_object_or_404(queryset, uuid=self.uuid) return obj However, I'm, not seeing that the uuid kwarg from path() is not being passed into the class ... that is, self.kwargs is None, and self.uuid is also None ... Would anyone be able to help with understand how I can get MyCustomGraphQLView to inherit the setup() from from django.views.generic import View ?? -
Keyczar: ModuleNotFoundError: No module named 'errors' in Python 3.8
I'm using django-encrypted-fields to encrypt models in the database, but I'm getting the ModuleNotFoundError: No module named 'errors' from keyczar, is there any solvations? -
django template, using {% with %} to set a list var
I need to hard set a list in django template. I know that I have to pass variables to the template, instead of creating them in the template, but I only have access to the template file. I'm using sendinblue with a custom template, and the only way to use custom params injected to the template is to use their api. I only need to hardcode some content in a list, and the content will dynamically appear depending on contact, I think that using an api only for this is overkill. -
image : None while successfully upload Django
I'm getting image url None while successfully uploading the image, i expected to get the image url which i sent to my server, but i'm getting the None value instead. Any help, would be much appreciated. thank you so much in advance. serializers.py class BulkImageSerializer(ModelSerializer): image1 = ImageField(required=True) image2 = ImageField(required=False) user_id = CharField(read_only=True) class Meta: model = BulkImage fields = "__all__" def create(self, validated_data): image1 = validated_data['image1'] image2 = validated_data['image2'] validated_data['user_id'] = User.objects.get(email=self.context['request'].user.email) img_obj = BulkImage.objects.create( image1 = image1, image2 = image2 if image2 else None, user_id = validated_data['user_id'] ) return validated_data views.py class BulkImageAPIView(APIView): permission_classes = (IsAuthenticated,) def post(self,request,*args,**kwargs): user = request.user data = request.data serializer = BulkImageSerializer(data=data, context = {'request': request}) if serializer.is_valid(): serializer.save() return Response({ 'message' : 'Image upload successfully', 'data' : serializer.data, },status=200) return Response(serializer.errors,status=400) output: { "message": "Image upload successfully", "data": { "image1": null, "image2": null, "user_id": "employee01gmailcom" }, } -
How to insert multiple foreign key values in django?
i've tried using bulk_create but i couldn't insert the foreign key value, i want to add 100 bikes with about 20 stations class Bike(models.Model): ID_Bike = models.CharField(primary_key=True, max_length=120) Belong_Station = models.ForeignKey( Station, on_delete=models.CASCADE, related_name='listBike') def __str__(self): return self.ID_Bike class Station(models.Model): name_Station = models.CharField(max_length=120) latitude = models.FloatField(max_length=120) longitude = models.FloatField(max_length=120) address = models.CharField(max_length=120, default="") def __str__(self): return self.name_Station -
Initialize base class with data from derived class with django Model
Is there any way to inherit a django model and initialize a base class field with data in the derived class, like this : class InitialModel(models.Model): evolution_list = ('1', '2', '3') version = models.CharField(max_length=2, choices=evolution_list) # choices will be : '1', '2', '3' class Meta: abstract = True class NextModel(InitialModel): evolution_list = ('4', '5', '6') # version : choices will be : '1', '2', '3' # wanted version choices are : '4', '5', '6' Thanks in advance! -
Iterate over django m2m through model objects
I have the following ManyToMany relationship in my project: class Borrador(models.Model): nombre = models.CharField( max_length=40, help_text=_('Nombre para identificar al borrador.') ) productos = models.ManyToManyField( Producto, through=Articulo, ) class Articulo(models.Model): producto = models.ForeignKey( Producto, on_delete=models.SET_NULL, null=True ) borrador = models.ForeignKey( 'Borrador', on_delete=models.SET_NULL, null=True ) unidades = models.IntegerField( default=1 ) class Producto(models.Model): nombre_amistoso = models.CharField( max_length=40, help_text=_('Nombre corto para identificarlo facilmente.'), verbose_name=_('Pseudónimo') ) nombre_fabricante = models.CharField( max_length=60, help_text=_( 'Nombre largo que le da el fabricante al producto.' ), verbose_name=_('Nombre real') ) fabricante = models.ForeignKey( 'Fabricante', on_delete=models.SET_NULL, blank=True, null=True ) # etc... As you can see, Articulo model acts as a through intermediary model to retrieve additional info. I'm trying to iterate over all the Articulo objects associated with a given Borrador object. At the moment I got it working by doing this: class Borrador(models.Model): # [...] def tramitar(self, usuario, solicitar=False): articulos = self.productos.through.objects.filter( borrador=self ) for articulo in articulos: # do stuff My first attempt was the one below, but it returns all Articulo objects in the database articulos = self.productos.through.objects.all() for articulo in articulos: # do stuff Is there a better way to do this? I imagined a simple self.productos.through shoul work, but it isn't the case... Thanks in advance! J. -
Expected a list of items but got dict djangorestframework
I am making a quiz application using DjangoRestFramework and ReactJS and I am coding my serializers for my Create quiz page. In my application, I have a Question model, a Game model which is the Quiz, and an Option model. The Problem My data Here is the data I have that I am deserializing: data = { 'name': 'Quiz Name', 'questions': { 'text': 'Question 1', 'options':[ {'text': 'option 1', 'is_correct':False}, {'text': 'option 1', 'is_correct':True}, ] } } I run this in the shell: >>> serializer = CreateGameSerializer(data=data) >>> serializer.is_valid() False >>> serializer.errors {'questions': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "dict".', code='not_a_list')]}} As you can see, I am getting Expected a list of items but got type "dict". I am not sure what this error means and I searched SO but didn't find anything relevant. My Files I have included some of my models and serializers to help solve the problem. models.py class Game(models.Model): name = models.CharField(max_length=100, default='') code = models.CharField(max_length=100, default=generate_unique_code, unique=True) host = models.CharField(max_length=50, unique=True) def __str__(self): return self.code class Question(models.Model): text = models.CharField(max_length=100) order = models.IntegerField(default=0) game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.text class Option(models.Model): text = models.CharField(max_length=100) is_correct = models.BooleanField(default=False) question = … -
How to set the room availability to False after I selected a room in django
Im currently developing a Hotel Management System and I would like to set the availability of room to False after i choose it on reservations form. Here is my codes : models.py class Room(models.Model): room = ( ('Standard Room' , 'Standard Room'), ('Deluxe Room', 'Deluxe Room'), ('VIP Room', 'VIP Room') ) id = models.AutoField(primary_key=True) room_type = models.CharField(max_length=100, choices=room , verbose_name = 'Type of Room') room_no = models.PositiveIntegerField(verbose_name = 'Room No', unique=True, help_text = "Should be unique and not existing room no") rates = models.DecimalField(max_digits=10, decimal_places=2, verbose_name = "Rates per Room") available = models.BooleanField(default=False, verbose_name="Available") def __str__(self): return f"{self.room_type}" + " | " + "Room " + f"{self.room_no}" class Reservations(models.Model): room = ( ('Standard Room' , 'Standard Room'), ('Deluxe Room', 'Deluxe Room'), ('VIP Room', 'VIP Room') ) customer = models.ForeignKey(User, on_delete = models.CASCADE, related_name="reservation_user" ) name = models.CharField(max_length = 255, verbose_name = 'Customer Name') address = models.CharField(max_length = 255, verbose_name = 'Address') email_address = models.EmailField(verbose_name = 'Email Address') contact = models.CharField(max_length = 255, verbose_name = 'Contact No') type_of_id = models.CharField(max_length = 255, verbose_name = 'Type of ID') id_no = models.CharField(max_length = 255, verbose_name = 'ID No') no_of_days = models.CharField(max_length = 255, verbose_name = 'No of Days') check_in_datetime = models.DateTimeField(auto_now_add=False, verbose_name = … -
Почему PUT и PATCH в данном случае дают одинаковый результат?
Необходимо реализовать PUT и PATCH методы. именно и то и другое. Прочел, что PUT должен очистить не переданные ему аргументы, а PATCH именно внесет изменения в указанное поле. Данный метод работает как PATCH. **serializers.py** class ReadOnlyUserSerializer(serializers.ModelSerializer): first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=150) is_active = serializers.BooleanField() class Meta: model = CustomUser fields = [ 'id', 'username', 'is_active', 'first_name', 'last_name', 'last_login', 'is_superuser', ] def update(self, instance, validated_data): instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_active = validated_data.get('is_active', instance.is_active) instance.save() return instance **views.py** class UserViewSet(ListAPIView): # Allow only authenticated users to access this urls permission_classes = [IsAuthenticated, ] serializer_class = ReadOnlyUserSerializer def patch(self, request, **kwargs): saved_user = CustomUser.objects.get(pk=kwargs['pk']) data = request.data serializer = ReadOnlyUserSerializer(instance=saved_user, data=data, partial=True) if serializer.is_valid(raise_exception=True): saved_user = serializer.save() return Response({ "success": f"User with username '{saved_user}' updated successfully"}) Как написать метод для PUT ? как я понял, если передать Postman-ом PUT http://127.0.0.1:8000/api/v1/users/6/ {"first_name": "Lama"} , остальные поля, не указанные в теле запроса, должны очиститься... -
Django with HightChart , unable to print the x -axis
I am a newbie in django and python, trying to create a simple column bar chart using django queryset and hightchart.js I am able to successfully print the data but I unable to print the x-axis. Model(Sitting) with following fields user,current_score,quiz I would want to display the chart with Students Score for particular score in percentance. I have tried to change the x axis but of no avail. My code below: def chart_data(request): dataset = Sitting.objects.filter(quiz__owner=request.user).values('user__username','current_score','quiz') dataset.query.group_by=['quiz'] #print(dataset) students=Sitting.objects.filter(quiz__owner=request.user).values_list('user__username') #students.query.group_by=['user__username'] studentlist=list(students) print(studentlist) chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Quiz Result'}, 'xAxis': { 'categories': [ /* What to write here */ ], 'crosshair':'true' }, 'series': [{ 'name': 'Test Quiz 1', 'data': list(map(lambda row: {'name': row['user__username'],'y': row['current_score']}, dataset)) }] } #print(chart) return JsonResponse(chart) I am having hard time to switch between list , dictionary, json representation. Any good help links ? -
strftime model object and display in html template
Good day, I want to strftime the created model instance and display it in the HTML template(as a transaction_id). But I don't seem to get it right. Thanks for your help. models.py class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) phone_number = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) braintree_id = models.CharField(max_length=150, blank=True) coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL) discount = models.IntegerField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100) ]) views.py def order_list(request):#datetime.now().strftime("%Y%m%d%H%M%S") transaction_id = Order.objects.get(created) orders = Order.objects.all() current_user = request.user success = Order.objects.filter(user=current_user.id).filter(paid=True) fail = Order.objects.filter(user=current_user.id).filter(paid=False) return render(request, 'orders/order/order_list.html', { 'success': success, 'fail': fail, 'current_user': current_user, 'orders':orders, 'transaction_id':transaction_id, }) html <p class="card-text"> <mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction_id}}</mark> </p> -
OSError: libgdal.so.27: cannot open shared object file: No such file or directory
I built a docker file that installs gdal and proj library on CentOS8. After successfully installation of all dependencies, when i run my docker image i get OSError: libgdal.so.27: cannot open shared object file: No such file or directory. Please how do i rectify this ? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/devuser/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/devuser/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/devuser/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/devuser/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/devuser/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/devuser/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/devuser/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/devuser/.local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/devuser/.local/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
how to I make the toasts disappear after certain time
So the toasts are working fine how it's supposed to except some "class-based toasts" are like permanent doesn't disappear after 2 secs, like the 'warning toast'. I want them to show up for a certain time and then make them disappear and all of them should work the same. Thnx for any help! Getting a console error as such "messages.js:4 Uncaught TypeError: Cannot read property 'style' of null at showToast (messages.js:4) at messages.js:17" let margin = 10; const showToast = (type) => { const toast = document.getElementById(`toast-${type}`); toast.style.display = 'block'; toast.style.marginBottom = `${margin}px`; margin += toast.clientHeight + 5; hideToast(toast); } const hideToast = (toast) => { setTimeout(() => { toast.style.display = 'none'; margin -= toast.clientHeight + 5; }, 2000); } showToast('success'); showToast('info'); showToast('warning'); showToast('error'); .success{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: forestgreen; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 20px rgba(0,0,0,0.3); } .info{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: 15px; background-color: blue; color: #FFFFFF; border-radius: 10px; text-align: center; z-index: 2; box-shadow: 0 0 20px rgba(0,0,0,0.3); } .warning{ display: none; position: fixed; bottom: 0; margin-bottom: 10px; margin-left: 4%; font-family: Arial; padding: …