Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use npm library for django on runserver environment
I made static folder in my root project. in settins.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Install npm library under static directory. myproject/static$ npm -i js-cookie then There comes the files like this myproject/static/node_modules/js.cookie/dist/js.cookie.min.js then run server myproject$ python manage.py runserver then use in template.html However this shows the error GET http://localhost:8000/static/node_modules/js.cookie/dist/js.cookie.min.js net::ERR_ABORTED 404 (Not Found) I have two quesitons. Is it good practice to use npm library under django project?? Maybe runserver doesn't use mypoject/static? -
Django ORM for loop to get queryset
I am trying to use for loop to get list of author with the number of books writing and author with the title of book wrote. Here is my models.py class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title I have tried to loop through like this: for a in Author.all(): books = a.book_set.order_by('author') print(books) I get the authors as they are in DB. Also, for book in book_set.iterator(): ... print(book.title) I got the list of all books. I use author_list = Author.objects.order_by("book").count() which gave the number of author. How can I loop through the DB and get the Author with number of books, and Authors with book title wrote. -
Image and CSS pre loading in Django
I am developping a website with Django, hosted on Heroku, and still fairly new to it. I published my application, and notice a problem when navigating on the hosted website : Whenever you load a new page, it looks like images and css are reloading completely. For a short time (less than 1 second), It creates some king of glith on my menu bar because buttons are moving (because the image is missing) and changing color (because css is missing). What would be a proper way to handle this ? Is it possible to store those image and css in somme kind of cookie on the user browser ? Also, when i run the website on my localhost, i don't experiment the problem. Thanks for your help !! -
Django Drf: generate an 8 digit unique number in the user serializer
I have a field in my users model that will only be utilized for a Certain type of user student_id = models.CharField(_("student id"), validators=[ MinValueValidator(10_000_000_000), MaxValueValidator(99_999_999_999) ],unique=True, max_length=8, blank=True, null=True) when creating a user in the serializers.py file i tried the below code but didn't work def create(self, validated_data): def create_new_ref_number(): not_unique = True while not_unique: unique_id = randint(10000000, 99999999) if not User.objects.filter(student_id=unique_id): not_unique = False instance = User.objects.create( student_id=create_new_ref_number, firstname=validated_data['firstname'], middlename=validated_data['middlename'], lastname=validated_data['lastname'], age=validated_data['age'], phone=validated_data['phone'], ) after saving the user the student_id field is populated with the following string <function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950> -
Django gives Secret key must not be empty error
I am having this issue when I try to run the server in Pycharm. I am new to Django and downloaded this project as a backend for my react application. I have generated a Secret Key using: from django.core.management.utils import get_random_secret_key print(get_random_secret_key()) exit() I added this Secret key to settings.py file as well. Error Log which I get: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
How to block rows on read and write operations?
I have a model that counts how many operations were done by a user. (It's simplified for an example) User = get_user_model() class UserOperationCounter(models.Model): count = models.IntegerField(default=0) user = models.OneToOne(User) I have a context manager that is fetching a counter object for a user and increments the counter param after the exit @atomic() class IncrementCounterContextManager: def __init__(user_id): self.operation_counter = UserOperationCounter.objects.filter(user_id=user_id).select_for_update().get() def __enter__(): print(f"Fetch counter={operation_counter.counter} for user={operation_counter.user.id}") return self.operation_counter def __exit__(): self.operation_counter.count = F("count") + 1 self.operation_counter.save(update_fields=["count"]) self.operation_counter.refresh_from_db() print(f"Set counter={operation_counter.counter} for user={operation_counter.user.id}") Let's assume I want to use the context manager each time the user does some specific action on a platform and then I want to send him a notification with the message: "You have done <counter> hidden actions on our platform". select_for_update() works perfectly in scenarios when I want to update a Counter object at the same time, but the row is not locked for reading. Here is an example: def send_notification(counter, user_id): print(f"Send notification with counter={counter} to user={user_id}") user_id = 1 with atomic(): with IncrementCounterContextManager(user_id=1) as usr_counter1: send_notification(usr_counter1.counter, usr_counter1.user.id) with IncrementCounterContextManager(user_id=1) as usr_counter2: send_notification(usr_counter2.counter, usr_counter2.user.id) When I check logs I will see something like: Fetch counter=0 for user=1 Fetch counter=0 for user=1 Send notification with counter=0 to user=1 … -
Pivot table in django admin
good day There is a user and a task model, combined with a ForeignKey The task model has a type field - the type of the task, in which several variants of types are written, let it be 1, 2, 3 And actually further the question, I need to create a table with the number of tasks, that is, how many tasks of type 1, type 2 and type 3, filters are also needed by the start and end time of the task, and then export to Excel Here's how best to solve this problem, create a new model, or is it better to do something differently? With the creation of the model, there are questions about the constant updating of the database, it seems to me that this is not very good, now it is done so that there is a model field of the model Type 1, Type 2, Type 3 and then with the help of filters, tasks are obtained through the user and filtered, and then count () is calculated, but it can be done more correctly, so to speak, without unnecessary database operations. I use django, django-jet for the admin area -
Saving dictionary data to django model problem, error message = AttributeError("'dict' object has no attribute '_meta'")
I have a problem, saving a dictionary data to django model. Did I need to input sqlite3 query somewhere? Please teach me how can I solution this problem. received dictionary data {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Error message {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Unexpected e=AttributeError("'dict' object has no attribute '_meta'"), type(e)=<class 'AttributeError'> modles.py class Data(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) temp = models.FloatField(default=0.0) humidity = models.FloatField(default=0.0) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class DataSerializer(serializers.ModelSerializer): id = serializers.IntegerField(write_only=False) class Meta: model = Data fields = '__all__' snd_clienet.py data = Data( id = 20, author = User.objects.get(username='labovming'), title = 'random data', temp = random.random()*300, humidity = random.random()*12, created_date = timezone.now() ) serializer = DataSerializer(data) msg = JSONRenderer().render(serializer.data) rcv_server.py while msg: stream = io.BytesIO(msg) data = JSONParser().parse(stream) serializer = DataSerializer(data=data) # create new instance serializer = DataSerializer(data, data=data) # update 'data' # serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data serializer.is_valid() **<<< Validation fail ** serializer.errors serializer.validated_data **<<< Empty ** try: serializer.save() **<<< Error occur here ** print(f'data added : {serializer}') if self.DBman.messageHandler(Name, msg.decode()) == -1: self.request.close() break msg = self.request.recv(1024) except Exception as e: print(f"Unexpected {e=}, {type(e)=}") break -
metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I am trying to implement multiple inheritance with Partitioned model and Aggregate Model class AdAgencyLocationPurposeAggregate(PostgresAggregateModel,PostgresPartitionedModel): PostgresAggregateModel: class PostgresAggregateModel(PostgresModel,metaclass=PostgresAggregateModelMeta ): PostgresPartitionedModel class PostgresPartitionedModel( PostgresModel,metaclass=PostgresPartitionedModelMeta ): -
Celery Scheduler not starting
I'm trying to setup scheduler but I got the following error "Unrecoverable error" from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings.prod') app = Celery('core') app.config_from_object("django.conf:settings") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Chicago' I was guided by https://realpython.com/asynchronous-tasks-with-django-and-celery/ Here are two photos of my errors -
Django static files deployed from AWS S3
My sidebar navbar doesn't get the right styles user/main.css ul.no-bullets { list-style-type: none; margin: 0; padding: 0; } home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} <div class="container"> <div class='row'> <div class="col-xs-12 col-md-3"> {% block sidebar %} {% include 'sidebar.html' %} {% endblock %} </div> <div class="col-xs-12 col-md-9"> Some page </div> </div> </div> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} sidebar.html {% block content %} <nav id="sidebar"> Hi {{ user.username }}! <img class="profile-pic" src="{{request.user.profile_pic.url}}" > <ul> <li><a href="/">Dashboard</a></li> <li><a href="/">Messages</a></li> <li><a href="/">Documents</a></li> <li><a href="{% url 'logout' %}">Log Out</a></li> </ul> </nav> {% endblock %} base.html <!DOCTYPE html> {% load static %} <html> <head lang="en"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--Css Style --> <link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!--Font Link--> <title>{% block title %}Base{% endblock %}</title> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> -
How to serialize class into json (class is not in model)
I have simple class class City: def __init__(self, key): self.key = key def distance(self): distance = Distance.objects.get(id=self.key).distance return distance def __repr__(self): return "(" + self.key + ")" And in my view class as API def get_route(request): res = {} res['cities'] = [City(1),City(2),City(3)] return Response(res) it returns the list of class City However this shows the error Object of type City is not JSON serializable __repr__ could be used for representing class. However, it's not work for json. How can I solve it ?? -
Django Custom Admin Users
So I want 3 types of users: Admins, Doctors, and Patients They should possess the following attributes and only admins shall access the /admin routing so they should possess is_staff, is_superuser to determine if it's a patient or doctor. name, pw, email, phone, profile_pic, and date_created are other attributes they should possess. So I need to add parameters to the existing auth in admin.py from django.contrib.auth.models import User class Patient(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name -
username with `james i. adams` not accepted with django routers
I have registered routers for user model, which has viewset that has lookup_url as username. The username james adams is accepted by the router, but getting below error for james i. adams django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with keyword arguments '{'username': 'james i. adam', 'version': 'v1'}' not found. 4 pattern(s) tried: ['(?P<version>(v4))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v4))/users/(?P<username>[^/.]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?$'] Can someone guide me, how can I allow such username for url patterns with routers registered? Thanks in Advance -
How to Filter foreign key related models using datetime range
I'm trying to create a reservation system and I want to query all available tables. So, what I did is as follows, ... date_time = request.data.get('date_time') date_time = datetime.strptime(date_time, '%b %d %Y %I:%M%p') num_of_attendees = request.data.get('num_of_attendees') tables = Table.objects.filter(~Q( tablereservation__date_time__range=[date_time, date_time + timedelta(hours=2)]), num_of_chairs__gte=num_of_attendees ) ... But it returns all the table objects. My models, class Table(models.Model): """ Holds table details """ num_of_chairs = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) class TableReservation(models.Model): """ Holds table reservation details """ date_time = models.DateTimeField() table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{}-{}'.format(self.table, self.user) But I want is to get only the table objects that aren't reserved in the given date-time range. Any help is greatly appreciated. -
Django-Import-Export assign Field to specific column
I have a working form which exports all data to xls using Resource and Fields from the django-import-export package. But now I need to go a bit further and make it a bit more advanced. I need to export all data to an existing Excel template, assigning each field to a specific column, as in, for instance: Field 1 needs to be filled in B3, Field 2 in C4 etc. etc. I'm thinking after_export() can be used here but the docs dont go into detail how to use this method. Does anyone have some experience with this package? I'm not using the admin integration. -
ListCreateAPIView is not letting post data
I'm trying to create an API where I will upload image throw API end point, My Model has only one imageField. Please checkout the code below Model: class Image(models.Model): image = models.ImageField(upload_to="media", default="default.png", blank=True, null=True) def __str__(self): id = self.id return f'image-{id}' Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] Views: from rest_framework.generics import CreateAPIView, ListCreateAPIView from home.models import Image from .serializers import ImageSerializer class ImageListCreateView(ListCreateAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer Urls: from django.urls import path from .views import ImageListCreateView urlpatterns = [ path('image/', ImageListCreateView.as_view(), name='image'), ] But if I visit the url '127.0.0.1:8000/api/image/' It only shows the data. not letting me post new data. -
How to integrate django to Elastic App Search
I have doing a project of e-commerce and I need to integrate Django and Elastic App Search. How to integrate -
django many to many queriying
I am building an e-commerce website using Django, my models is like bellow : class ProductAttribute(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) attributes_values = models.ManyToManyField(AttributeValue,verbose_name="Liste des attributs") stock = models.PositiveIntegerField() price = models.PositiveIntegerField(verbose_name="Prix") image = models.ImageField(blank=True,null=True,upload_to="products") class AttributeValue(models.Model): attribute=models.ForeignKey(Attribute,on_delete=models.CASCADE,verbose_name="Attribut") value = models.CharField(max_length=50,verbose_name="Valeur") class Attribute(models.Model): name = models.CharField(max_length=50,verbose_name="Nom") my view.py def getatts(request,product_id): products_with_attributes=ProductAttribute.objects.filter(product__id=product_id) res=#..... missing code to get attributes with values return res In the front end i want to retrieve attributes of a particular product to get them by order, to use them in select (ex:size,color choices) , for example if the query set of ProductAttribute is like: [{id:1,product:1,attributes_values:[3,4],...},{id:1,product:1,attributes_values:[5,6],...}] the result in JSON would be like so: { result:[ { key: "color", values: [ {id: 1, value: "Red", choices:{ key:"size", values:[{id:3,value:"L"},{id:4,value:"XL"}] } }, {id: 2, value: "Black", choices:{ key:"size", values:[{id:5,value:"M"},{id:6,value:"XXL"}] } }, ] } ] } -
Problem while trying to create dynamic html
Why don't I get the dynamic text that used in the views.py? My views.py code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = { 'name' : 'Amlan', 'age' : 23, 'nationality' : 'Indian' } return render(request, 'index.html', context) My index.html code: <h1> Hello {{name}}<br>You are {{age}} years old<br>You are {{nationality}} </h1> When I run the server I get: Hello You are years old You are -
DRF - from django.conf.urls import url in Django 4.0
I've a project in django 3.2 and I've updated (pip install -r requirements.txt) to version 4.0 (new release) and I've currently the below error when I run the server in a virtual environment. I use DRF. Can't import => from rest_framework import routers in urls.py from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -
Disable querying a field in Django Rest Framework
Here is the model class. Where categories is a nested mptt model tree. class MyModel(models.Model): categories = models.ManyToManyField(Category) # to another nested model (self referncing tree) The serialzier is a simple one class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel exclude = ['categories', ] When serializing the Model object, on sql queries are executed to fetch categories. I dont want the categories field in the response, so I excluded it in the serializer but the categories table is queried when serializing. serializer = MyModelSerializer(MyModel.objects.first()) How can I disable queries to that table when doing this particular operation? Thanks. -
Applying date filter on a char-field that stores the date-time in string in django?
I have this field on a model X: class Details(models.Model): start_time = models.CharField(max_length=25, null=True, blank=True) Now, one problem arises that I need to apply the date filter on this. is there any way to solve this. I want to do something like this Details.objects.filter(start_time__time=some_time) -
How to return back to the same page when we use user_passes_test decorator in Django
When I sign in or log in to my account, I do not want to go back to the login page or registration page by giving the URL in the address bar. What I want is to stay on the same page even after giving the registration or login page URL. For that, I have used the user_passes_test decorator in the views.py file. Also, I set login_url in the user_passes_test decorator as return redirect(request.META['HTTP_REFERER']). At that time I got a Page not found (404) error. views.py from django.contrib.auth.decorators import user_passes_test @user_passes_test(user_is_not_logged_in, login_url="return redirect(request.META['HTTP_REFERER'])", redirect_field_name=None) def register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserForm() return render(request, 'register.html', {'form': form}) Can anyone suggest a solution to solve this issue? -
style.css file is not working nor any error message is displaying in terminal in django
I have looked around on this site as well as others and still have not found a solution that works for why django is not loading my css file even not showing any error in terminal even in debug console. my settings.py file: STATIC_URL = 'static/' my html file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> My file tree: App -static -css -style.css -templates -index.html INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] Any help would be greatly appreciated. I tried using the STATIC_ROOT as shown on a different thread but there was no change with that.