Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count objects using Django Rest Framework
I have url api/v1/posts/. If we use GET request from that url, we can see all objects. For example: { "count": 1, "next": null, "previous": null, "results": [ { "url": "http://127.0.0.1:8000/api/v1/posts/11/", "id": 12, "name": "Sample name", "type": "Shirt", "collection": "Winter 2020" } ] } We need to create functional - We can create GET request with filter. In our case, we need to filter "type": "Shirt" and we can see "Collection" with count (count shirts from all collections) For example: { "collection" : "Winter 2020" "result" : [ { "count": 12 } ] } Etc... How to create it using Django Rest Framework? -
Unable to Proxy to Websocket via Nginx inside a VM
I am working with nginx and django channels. The Django app has an Http connection and a WebSocket connection. The diagram below shows the three scenarios and how they work. Situation 1 - Everything is setup locally and the client can send http requests and create a websocket connection to the django app. Situation 2 - Only the django app is setup on the VM and the client can send http requests and create a websocket connection to the django app. Situation 3 - Everything is setup in a VM (VirtualBox) and the client can send http requests and CANNOT create a websocket connection to the django app. The django app responds with a 404 error for the websocket connection attempt. This is the nginx config Note: The Django app is being run in a docker container, which is called 'backend'. worker_processes 1; events { worker_connections 1024; } http { upstream backend { server backend:8000; } server { listen 80; location /backend/ { proxy_pass http://backend; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /static/ { proxy_pass http://backend/static; } } } The logs for the django app show the http … -
django manage.py - no module named 'jquery'
There are some similar questions here already, but having tried some of the solutions there with no success I'll outline my particular issue: I'm trying to move my Django application from my Windows to Linux. I've SFTPed the project files over (except venv and staticfiles) and set up a new venv from the original requirements. I'm trying to run manage.py to test the server but it's throwing out the following error: Of course I've done my reading, and this error comes from running through the INSTALLED_APPS list, but jquery is not one of those items. For reference: INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'data_license_request.apps.DataLicenseRequestConfig', 'webpack_loader', 'graphene_django', ] I am running this with the virtual environment activated. I feel that this might have something to do with dal, but with jquery installed globally on the server I just don't get it. Any help or further questions are appreciated. -
Save a ForeignKey "child" without saving the "parent" first?
Suppose I have a view for saving an order to a database based on cart contents: def cart_checkout(request): order = Order() order.first_name = 'x' order.last_name = 'y' order.address = 'z' order.save() cart = Cart(request) for product_id, product_quantity in cart: product = Product.objects.get(pk=product_id) order_item = OrderItem() order_item.order = order order_item.name = product.name order_item.price = product.price order_item.amount = product_quantity order_item.save() order.update_total_price() # updates the Order total price field with the sum of order items prices order.save() return HttpResponse('Checked-out!') As you can see, I am calling order.save() twice in this view: first to create an Order instance the OrderItems can be attached to in the for loop, and then to update the total price of the order based on order items in it. If I removed the first .save(), I would get an error on the second one telling me the order needs to be saved first. Calling the .save() method twice does not seem DRY enough to me. Is there a way to do it only once? Note that I am not subclassing ModelForm, so I cannot use .save(commit=False). Also, I do not want to just hide the save() method in the update_total_price() method. Models.py: from django.db import models from .mixins import … -
Django - get_inital in CreateView doesn't work as expected
I have a CreateView, I want it to be called and filled with an initial data: class StartGame(PermissionRequiredMixin, CreateView): model = Author fields = {'date_of_death'} permission_required = 'catalog.can_mark_returned' def get_initial(self): # Get the initial dictionary from the superclass method initial = super(StartGame, self).get_initial() # Copy the dictionary so we don't accidentally change a mutable dict initial = initial.copy() initial['card'] = '0' print(initial) initial['bb'] = '0' print(initial) return initial But when I call it from urls.py it works only as. I tried fill 'card' differently: '0',"0",0 - it is all the same: Model looks this way class Author(models.Model): """Model representing an author.""" card = models.CharField(max_length=100) second_card = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) bb = models.IntegerField(default=0) voted_id = models.CharField(max_length=1000,default="zero") I just can't understand why it is not working -
How to add a value to a form field before rendering the form?
I'm building a website whose purpose is to deliver food. I have a model "Plat" representing a meal and a model "Commande" representing an order. In the website, the user can look at a meal, then click on a button "make an order" and finally fill a form with the order details. "Commande" has multiple fields and one of them is "plat" that link the order to the meal. My problem is that I need to fill the "plat" field of the "Commande" model before rendering the form because I have a validation rule that depends on a field of the "Plat" model : in the "Commande" form, the customer can choose the number of parts of the meal he want, and if this number is greater than the number of parts availables (parts_available is a filed of "Plat"), it raises an error. I have tried to do it this way (see below) but that doesn't work, when the customer save the "Commande" form, it raises an AttributeError because it try to access a field of plat but plat is equal to None. Do you have any idea how I can do what I want ? Thanks in advance ! … -
Create super admin user credentials in Django admin
Is there any way to create a super admin in the Django admin UI itself? I'm using my own model by inheriting from AbstractUser class. I have difficulty understanding how I can provide the password by my own so that the user will use those credentials to login. Basically I want to create a user without the need of manage.py. -
Docker volume does list my media contents in ngnix container
I am trying to serve Django media files via Nginx, where data will be uploaded via my backend application. Below is the configuration which I am trying via docker-compose. Django configuration: MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder MEDIA_URL = '/media/' urlpatterns = [current url ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) docker-compose.yml middlewareapi: container_name: middlewareapi volumes: - /opt/media_data:/home/test/mwapi/media - api_data:/test/cbl/mwapi nginx_custom: container_name: nginx_custom ports: - "8080:8080" - "8443:8443" volumes: - api_data:/mw_api depends_on: - middlewareapi nginx_app.conf location /media { alias /mw_api/media; } We can upload files from my backend. But Nginx is not able to serve files for download, it is stating file not found error. when is try to list container "middlewareapi" lists all the data in the media folder: docker exec -it middlewareapi ls -la media but when I try to list the same with Nginx instance, it is responding with 0 bytes and no files are getting listed. docker exec -it nginx_custom ls -la /mwapi/media need some help in troubleshooting -
How to Query nested Foreign Key shared attributes wih Django
I have a structure of objects with 4 layers of nested Foreign key relationships. On each level, I have an owner attribute for that object. I need to query the entire tree for objects owned by someone, and return the object owned by them and their parents all the way to the top level, even if they are not owned by the person I am filtering by. class User: """only need to worry about id on this class""" class Level1: owner = models.ForeignKey(User) class Level2: owner = models.ForeignKey(User) parent = models.ForeignKey(Level1, related_name='level2') class Level3: owner = models.ForeignKey(User) parent = models.ForeignKey(Level2, related_name='level3') class Level4: owner = models.ForeignKey(User) parent = models.ForeignKey(Level3, related_name='level4') Being the owner of an object does not guarantee the ownership of the children, and visa-versa. I am hoping to return the following structure with a single DB query, in order to improve performance of my application. This query is executed very often, and a major bottleneck at the moment. The desired structure is: [ {id: 1, type: Level1, owner: owner_id children:[ {id: 1, type: Level2, owner: owner_id, children:[ {id: 1, type: Level3, owner: owner_id, children:[ {id: 1, type: Level4, owner: owner_id}, {id: 2, type: Level4, owner: owner_id}, ]}, ]}, … -
How to train a Keras model in Django
In my Django app, I allow the user to train their own binary classification model using Tensorflow Hub. The training task looks like this: import tensorflow as tf import tensorflow_hub as hub import numpy as np def classification_model_train_binary(): x_train = np.array(["Some test text", "Testing this text", "This is relevant to my test", "Cows don't fly", "One two three", "some text"]) y_train = np.array([1, 1, 1, 0, 0, 0]) model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1" def my_iterator(x, y): while True: for _x, _y in zip(x, y): yield np.array([_x]), np.array([_y]) hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[], dtype=tf.string, trainable=True) model = tf.keras.Sequential() model.add(hub_layer) model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=[20])) model.add(tf.keras.layers.Dense(1, activation='sigmoid')) model.summary() model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit_generator(my_iterator(x_train, y_train), epochs=5, steps_per_epoch=len(x_train)) print("THE END") I ran the code above in the following ways (same virtual environment for all tests): As standalone scirpt: successfully From a Django view: error (see below) From Django Shell: error (see below) From Jupyter Notebook using: python manage.py shell_plus --notebook: successfully Error Exception Type: TypeError at /classify/classifier/binary/ Exception Value: cannot create weak reference to 'gevent._local.local' object How come I am able to run as a standalone script and through jupyter notebook (with Django shell!) but not with the standalone Django shell? What do I need to do to make … -
Invalid syntax in get-pip.py and couldn't download pip successfully in window 7
currently using window 7 64 bit. python version 3.8.1 my pip isn't working properly pipand I'm facing many issues. help me out... get-pip.py shows the invalid syntax -
Error while starting Celery worker on django Error 10061 No connection could be made because the target machine actively refused it
I am working with django as a framework for my web application. For using celery I have installed django-celery, celery and celer[redis]. When it tried to start the celery worker it shows error Cannot connect to redis://localhost:6379/0: Error 10061 connecting to localhost:6379. No connection could be made because the target machine actively refused it.. Trying again in 6.00 seconds... I am using a windows laptop. How can I start the redis://localhost:6379/0 sever. This is the result of running the worker $ celery worker -A myemail.celery -l info -------------- celery@LAPTOP-ERVJPN6C v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Windows-10-10.0.18362-SP0 2019-12-30 19:35:13 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myemail:0x38d56d0 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . mailinglist.tasks.send_confirmation_email_to_subscriber [2019-12-30 19:35:14,763: INFO/SpawnPoolWorker-1] child process 17836 calling self.run() [2019-12-30 19:35:14,782: INFO/SpawnPoolWorker-4] child process 19512 calling self.run() [2019-12-30 19:35:14,782: INFO/SpawnPoolWorker-6] child process 6816 calling self.run() [2019-12-30 19:35:14,789: INFO/SpawnPoolWorker-8] child process 12316 calling self.run() [2019-12-30 19:35:14,793: INFO/SpawnPoolWorker-2] child … -
Django Unit test is giving Anonymous user while login
I've the below code for Django login Unit test. """This is the unit test case for form element""" from django.test import TestCase from django.contrib.auth.models import User class TestForm(TestCase): def setUp(self): self.credentials = { 'username': 'abhishek', 'password': 'Abhishek@12345'} User.objects.create_user(**self.credentials) def test_login(self): # send login data response = self.client.post('/accounts/login', self.credentials, follow=True) # should be logged in now print(response.context['user']) self.assertTrue(response.context['user'].is_authenticated) While I'm executing this Unit test through my command python ../manage.py test accounts.tests.test_form.TestForm It's giving the below error. Creating test database for alias 'default'... System check identified no issues (0 silenced). AnonymousUser F ====================================================================== FAIL: test_login (accounts.tests.test_form.TestForm) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Django\webapplication\accounts\tests\test_form.py", line 18, in test_login self.assertTrue(response.context['user'].is_authenticated) AssertionError: False is not true ---------------------------------------------------------------------- Ran 1 test in 3.391s FAILED (failures=1) Destroying test database for alias 'default'... Can somebody help me !!!! -
Django: check_password returns false, even if the password was saved as hash
I am using Django==2.1.5 My goal is a simple DRF based create user and login, but instead of login with username (and pw) i want to login with the email address+pw. Therefore I saved USERNAME_FIELD = 'email' in models.py, implemented my own backends.py where I overwrite authenticate, using check_password inside of it. As you can see in the code below, I am passing the password as plain text (from request), but it always returns False -> so authenticate returns None and i cannot login (the print line in views.py print ("login", email, password, user_logged_in) prints for example *login bla@bla.com test123 None). The user creation is working; users have is_active=true and an encoded password like "argon2$argon2i$v=19$m=512,t=2,p=2$bmJUV1RLWXVWRVdX$mTJwkk/E/e2b8xNd2ZJkAw". Another thing i would like to point out is that in admin ui the password field is editable and exactly the same as in the db (postgres). As far as I know, the password field in admin ui should be readonly and a little bit different - I don't know if this helps anybody but maybe it is an helpful information. For the migration process i had to add a default value for the password, since it must not be null (password field is in … -
How to make PUT ang GET method in Django for child model of User?
I have a default user model from django.contrib.auth.models import User and I want to add child model with interger field for every user. How to do it and make avalible PUT ang GET methods only for one parent user? User must be authorized (user must send token in header of request) Methods should be avalible by .../level/ path view.py class UserLevelView(APIView): permission_classes = (IsAuthenticated) def get(self, request): pass def put(self, request): pass urls.py urlpatterns = [ # other paths path('level/', UserLevelView.as_view()) ] serializer.py class UserSerializer(serializers.ModelSerializer): #ModelSerializer contains create and update by defautl class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): #reindefenition user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() Token.objects.create(user=user) return user def update(self, instance, validated_data): pass -
when i trying slug i am getting program() got an unexpected keyword argument 'slug'
when i tried the slug to my URL it is showing the error i dont know what is cause the problem i am new to the slug my html page URL path-- <a href="{% URL 'details' services.id %}"> url path('details/<slug:slug>/', views.details, name='details'), path('program/<slug:slug>/', views.program, name='program') model prgm--- class prgm(models.Model): image1 = models.ImageField(upload_to='images/', default='image1') image2 = models.ImageField(upload_to='images/', default='image2') slug = models.SlugField(max_length=250, default='title') def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) return super(prgm, self).save(*args, **kwargs) detail-- class services(models.Model): image = models.ImageField(upload_to='images/') title = models.CharField(max_length=200, default='title') slug = models.SlugField(max_length=250, default='title') def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) return super(services, self).save(*args, **kwargs) -
Model migrations using Django (cant migrate)
can anyone help me? I am trying to migrate some model classes to the built-in Django SQL database admin, but I am showing a type error when I try to migrate can you see what I am ding wrong?enter image description here -
I need help to get login using rest framework?
error looks something just like this KeyError: 'user' while i try to login every time this error message is shown.I have installed the Django Rest Framework .What's the best way to do a login using Rest Framework? my views class LoginAPIView(APIView): def post(self, request): serializer = LoginSerializers(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"status": status.HTTP_200_OK, "Token": token.key}) my serializers class LoginSerializers(serializers.Serializer): class Meta: model = User email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get('email', None) password = data.get('password', None) if email and password: user = authenticate(username=email, password=password) if user: data['user'] = user data['user'] = user return user return data -
How can I get cookies in django template without request?
I have a form. Need the after its send to the server the page refresh and shown message "Thanx for review". I'm us cookies for it, but I can't to get cookies in template def post(self, request, slug): from django.http import HttpResponseRedirect response = HttpResponseRedirect(request.path_info) response.set_cookie('review_added', 'yes') return response -
python manage.py runsever Error in MAC OS
Iam trying to run django project i get this kind of error zsh: abort python3 manage.py runserver am using django version 2.2.6 (venv) abc@abcs-MacBook-Pro core % python3 manage.py runserver zsh: abort python3 manage.py runserver (venv) abc@abcs-MacBook-Pro core % -
DJANGO: How to write a custom serializer that add a field from a related model?
Models: class Subject(models.Model): db = 'default' subjectName = models.CharField(max_length = 100) cohortID = models.ForeignKey(Cohort, on_delete=models.CASCADE, related_name='subjects') teacherID = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='subjects', null=True) class Cohort(models.Model): db = 'default' school_creator = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name='cohorts') mainTeacherID = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, related_name='mainCohorts') class_name = models.CharField(max_length = 100) Serializer: class SubjectSerializer(serializers.ModelSerializer): class Meta: model = models.Subject fields = ('subjectName', 'teacherID', 'pk',) This is a response using serializer above: {"subjectName":"Maths","teacherID":2,"pk":4} I would like to have: {"subjectName":"Maths","teacherID":2,"pk":4, "cohortName" : "4 B"} cohortName should be taken from model Cohort.class_name. I guess it is possible to do that because Subject is connect to Cohort by ForeignKey Subject.cohortID. I have tried to add some custom Serializer: class SubjectCohortSerializer(serializers.ModelSerializer): cohortName = serializers.SerializerMethodField(read_only=True) class Meta: model = models.Subject fields = ('subjectName', 'teacherID', 'pk','cohortName') def get_cohortName(self, subject): return models.Cohort.objects.get(pk=self.context['request'].cohortID.className) But surely I am doing something wrong, and it is really difficult to grasp what is happening in a serializer above. -
How to pass initial data from QuerySet to formset?
I'm developing a Property Management System, right now I'm working on an app named Property check, which basically saves info about inspections made on some properties. A helpful user told me that I could achieve it using formsets. I'm trying to create a formset with my model TaskCheck. Every TaskCheck has a specific Task that belongs to one property. So this is what I've created: views.py def add_taskcheck(request, property_pk, pk): tasks = Task.objects.filter(property=property_pk) tasks_list = Task.objects.filter(property=property_pk).values('task') TaskCheckFormset = formset_factory(TaskCheck, form=TaskCheckForm, extra=0) if request.method == 'POST': #do something else: formset = TaskCheckFormset(initial=task_list) context = { 'title':"Add Property Check", 'task':tasks, 'reference':property_pk, 'formset':formset, } return render(request, 'propertycheck/add-taskcheck.html', context) My form looks like this: In this case, the Task "Sofas: Check" does not belong to the instance property, so it shouldn't be there, and the field Task should be pre-filled as initial data. As far as I know from what I've read here I should pass initial data as a dict list. So I created "tasks_list" with .values() and tried to pass it as initial: tasks_list = Task.objects.filter(property=property_pk).values('task') formset = TaskCheckFormset(initial=task_list) So my questions are: How can I pre fill those fields with the queryset tasks? How can I limit the number of rows … -
JavaScript loading function script to display django static image
I have an image processing that takes some seconds and I want to show a loading gif and a text until it's done and the view changes. So, after selecting an image, when pressing the Submit button to upload it, I call the following JavaScript function: <script type="text/javascript"> function ShowLoading(e) { var div = document.createElement('div'); var img = document.createElement('img'); img.src = "{% static 'img/loading.gif' %}"; div.innerHTML = "Processing..."; div.style.cssText = 'position: fixed; top: 10%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #106087; border: 1px solid #000'; div.appendChild(img); document.body.appendChild(div); return true; } and the form for uploading image looks like: <form onsubmit="ShowLoading()" method="post" enctype="multipart/form-data"> The problem is that after pressing the Submit button, the div and the text appear, but the photo doesn't. I have the loading.gif file in my /static/img/ I also included {% load static %} in my code header. (and the path to static files is set in settings - and it's working in html code) The JavaScript script is in the same html file as the form that's using the function. -
I am using django smart selects library for ChainedManyToManyField but the dropdown is not visible for this field?
Uncaught ReferenceError: chainedm2m is not defined at initItem (bindfields.js:14) at HTMLSelectElement.<anonymous> (bindfields.js:25) at Function.each (jquery.min.js:2) at bindfields.js:24 at dispatch (jquery.min.js:3) at r.handle (jquery.min.js:3) I am not able to see data in dropdown at django admin panel? sub_region = ChainedManyToManyField(SubRegionManagement,chained_field="region",chained_model_field="region") country= ChainedManyToManyField(CountryManagement,chained_field="sub_region",chained_model_field="sub_region", help_text="Please fill this field",verbose_name='Country') The above are my fields in django models -
Django get number of of likes group by category
My Model structure is given below from django.db import models class ArticleCategory(models.Model): name = models.CharField(('Name'), max_length=255) class Article(models.Model): category = models.ForeignKey('articles.ArticleCategory', null=True, blank=True, related_name='articles', on_delete=models.SET_NULL) class ArticleLike(DateBaseModel): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='user_likes') article = models.ForeignKey('articles.Article', on_delete=models.CASCADE, related_name='article_likes') I have a query like below from django.contrib.auth import get_user_model User = get_user_model() condition = """ SELECT ( SELECT COUNT(articles_articlelike.id) FROM articles_articlelike WHERE articles_articlelike.user_id = account_account.id ) AS "likes_count", "account_account"."id" FROM "account_account" """ users = User.objects.raw(condition) This gives me the queryset of users with their like count. Now what I am trying to do is add the top liked category to this query. This is to show the admin which category a user liked most. How can i create a query like this ?