Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override the default formfield for a read only foreign keys field in Django ModelAdmin?
I am overriding the default formfield of foreign keys on ModelAdmins as described here. However, I am not overriding it to return a subset, but instead to defer fields in order to optimize the performance. For example: class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.only("name") return super().formfield_for_foreignkey(db_field, request, **kwargs) It works for most of my use cases, but the problem occurres when the foreign key is set as a read only field. While debugging, I noticed that when it is set as read only, the field is never passed through formfield_for_foreignkey method and the query retrieving the foreign key selects all fields instead of only the necessary ones. In my case, some of the fields are too big causing an unecessary terrible performance. I also tried the second method described in the docs, using ModelForm.__init__(), but it is not really useful for my use case. -
WORKON is not recognized as the name of a cmdlet
PS C:\Users\HP\travelproject> workon myproject workon : The term 'workon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + workon myproject + ~~~~~~ + CategoryInfo : ObjectNotFound: (workon:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException your text Already installed virtual enivronment in cmd . -
How to change model attribute in template django?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) has_boss = models.BooleanField(null=True) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' And there are template for nested bosses: {%if employee.has_boss %} <div class="nested_leaf" <ul> {% include "tree_view_template.html" with employee=employee.boss employee.has_visited = True %} </ul> </div> {% endif %} <div class="leaf"> {% if not employee.has_visited %} <li> <{{ employee.id }}>{{ employee.name }} - {{employee.position}} </li> {% endif %} </div> Can i change attribute in django template? In this configuration i have an error with employee.has_visited=True -
django foreignkey and create index
Im currently working on a DRF api, and need to remove ForeignKey from model in models Note and Comment. I was told i need to replace the FK with an index in that column instead. Ive looked into the relationship and can't think of a way to maintain the many to one. Im working with a Postgresql db and Note as the parent model and comment as the child. My question- Is there an altenative way of making this happen(removeing the FK on both models and still maintaining the ManyToOne? and how would i replace the FK column with an index?) thank you for any possible help. Models.py class Note(models.Model): creator = models.CharField(auth.models.User, on_delete = models.CASCADE) content = models.TextField(max_length= 200) def __str__(self): return self.content class Comment(models.Model): content = models.TextField(max_length= 200) creator = models.ForeignKey( auth.models.User, related_name="comments", on_delete=models.CASCADE note = models.ForeignKey("Note", related_name="comments", on_delete=models.CASCADE) serializer.py class CommentSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") class Meta: model = Comment fields = ["uuid", "content", "creator", "notes"] class NoteSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Note fields = ["type", "content", "creator", "comments"] -
Why django filter is not working for not case sensitive search
I am trying to fetch the data from django models, where as TaskBlockers.objects.filter(task__project=1,task__team='Backend') gives queryset with 3 objects TaskBlockers.objects.filter(task__project=1,task__team='backend') gives empty queryset. it was supposed to return same for both the queries isn't it? if now why is this happening and how can I rectify it for both type of input. here are my models. class TaskBlockers(models.Model): task = models.ForeignKey(ProjectTask,on_delete=models.SET_NULL,null=True,related_name='task_id_related') blocker = models.CharField(max_length=100,null=False) class ProjectTask(models.Model): project = models.ForeignKey(Projects,on_delete=models.SET_NULL,null=True) team = models.CharField(max_length=10) task_title = models.CharField(max_length=200,null=False) task_desc = models.TextField(blank=True) -
How to give the data to serializer with JSONField
I have model and serializer with JSONField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) detail = models.JSONField(default=dict) def __str__(self): return self.user.username class ProfileSerializer(ModelSerializer): class Meta: model = m.Profile fields = '__all__' Then,I want to set the data to serializer class, However some how serializer.is_valid() faild. I have tested two pettern data1 data2 temp_data = {"data":"test"} data1 = {"detail":temp_data} # test_data1 data2 = {"detail":json.dumps(temp_data)} # test_data2 print(data1) # {'detail': {'data': 'test'}} print(data2) # {'detail': '{"data": "test"}'} instance = self.get_object() serializer = self.get_serializer(instance,data = data1) # or data2 if serializer.is_valid(): # serializer else: print("is_valid failed") What data should I give to this serializer? And is there any method to debug is_valid()? -
How to migrate a Django app with postgres database
I have just inherrited a jDango app with .tar.gz compression extention and a .sql file which is a postgreSQL database dump. My mission which I did not choose to accept is to somehow find its way onto AWS. I'm not familier with Django. I believe the app was built with the Ubuntu OS. I thought that maybe the best thing would be to get postgreSQL and Django working on my local machine. I have all working in vanilla on Windows, and Ubuntu (virtual box) and have set up Amazon Lightsail with a postgreSQL database.. I'm a bit stuck as to what to do next to migrate the app. Would it all be CLI/Cmd Prompt/Terminal or is there a procedure I should be using. I'm guessing it's not as simple as importing the database and then copying files over and replacing existing vanilla Django ones? Any pointers would be of great help. Thanks. -
How can i use django_channels and django_hosts libraries together?
I have added the django_channels library for realtime logic on my site. I have included the following websockets URL patterns (file my_project/asgi.py): application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( news.routing.websocket_urlpatterns ) ) ), }) Everything worked fine until I decided to configure wildcard subdomains using the library django_hosts(file my_project/hosts.py): host_patterns = patterns('', host(settings.DEFAULT_SUBDOMAIN, settings.ROOT_URLCONF, name='www'), host(r'(?P<p_category>\w+)', 'my_site.hostsconf.urls', name='category'), ) And after that I can't connect to the websocket using javascript: Is there a way to configure these two libraries so I can connect? I can't find the way to configure django_hosts to connect using the ws:// scheme. -
When logged in as a user, the cart does not clear after completing the transaction via paypal in my Django project. It works when not logged in
I recently completed a YouTube tutorial series from Dennis Ivy on building a Django-based ecommerce website. My website works except for 1 major bug. When the user is logged in and goes through the checkout process, the cart does not clear after completing the paypal checkout. When the user is not logged in ("AnonymousUser"), it works correctly. I'm struggling to find the source of this bug. Any suggestions? I'm including the parts of the code I think might be relevant. cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, 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) => { location.reload() }); } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', … -
Prefetch Related, Select Related on a Through Model in Django Admin Form
Several Duplicate Queries in Django Admin Form. I have models something similar to below examples. I am giving inlines in my django admin and I have declared prefetch related but still it is giving many duplicate queries on foreign key fields present in the inline model. I have tried .prefecth_related('b1','b1__a') etc... no luck on reducing the queries and the page is loading very slowly due to the amount of queries running class A(models.Model): name = models.CharField(max_length=10) b1 = models.ManyToManyField(B) class B(models.Model): name = models.CharField(max_length=10) class C(models.Model): name = models.CharField(max_length=10) class D(models.Model): name = models.CharField(max_length=10) class E(models.Model): a = models.ForeignKey(A, on_delete=models.DO_NOTHING) b = models.ForeignKey(B, on_delete=models.DO_NOTHING) c = models.ForeignKey(C, on_delete=models.DO_NOTHING) d = models.ForeignKey(D, on_delete=models.DO_NOTHING) class EInline(admin.TabularInline): model = E extra = 0 can_delete = False show_change_link = False def get_queryset(self, request): queryset = super(EInline, self).get_queryset(request).select_related( 'a', 'b', 'c') return queryset class Aadmin(admin.ModelAdmin): inlines = [EInline,] def get_queryset(self, request): queryset = super(Aadmin, self).get_queryset(request) queryset = queryset.prefetch_related('b1') return queryset -
How to generate a uml diagram from c++ source code dynamically
I am busy developing code that parses through c++ source code and examines the inheritance there. I want to have the program dynamically generate html for representing a UML class diagram of the source code being analysed. Some information: The program has been written in Python and the UI is a django webpage The program already extracts the relevant information and can display the files The class diagram is only for user reference so they can navigate the files with some insight I am looking into using mermaid and javascript for these purposes but am having some trouble. Any advise would be appreciated. How to create a dynamic UML-diagram from HTML Tables? This comes close to a solution but not quite. Right now I dynamically generate lists the store the relevant class information. -
Django select2 with ModelChoiceField/ createTag (how to create a create new record)
How do I handle using select2 with ModelChoiceField, but enable adding a new record I have the Select2 JS in place, and everything works well. I can use my queryset for the ModelChoiceField, and that works. However, if I try to add a new record all I get is the error "Select a valid choice. That choice is not one of the available choices". Which is true - in the view I tried to grab "ID 0" to then create a new record, but can't get past validation without the above error Also, if I do get this to work, it will provide the "0" ID, but ultimately I require the "term" for the new record, but can't see how this is done <script type="text/javascript"> $("#id_indoor_cooler").select2({ theme:"bootstrap4", search_fields: ['model_number'], tags: true, createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } return { id: 0, text: term, newTag: true, // add additional parameters, value: "myCustomValue" } } }); </script> -
Is there a way to see which libraries are being monkey patched when running celery with eventlet pool in a Django application?
I am currently running a Django project that offloads work to celery background workers. For CPU-bound tasks the fork pool is working great running like so: celery -A myApp worker -l INFO -E -n worker --concurrency=<CPU-core-count> However, with a growing set of long-running tasks mostly scraping APIs from background workers I am looking create a separate queue to make use of eventlet (or gevent pool) for better scaling these workloads. I am running eventlet it like so which starts the worker and seems fine when I test it. celery -A myApp worker -l INFO -E -n worker --concurrency=100 -p eventlet I have tested two different version setups for eventlet. First off with these versions: - Celery 5.1.0 - Eventlet 0.33 When running this setup I get the same error as reported here when making API polls + database queries in my workers:DatabaseWrapper objects created in a thread can only be used in that same thread Other suggestions have proposed simply updating eventlet and Celery to the latest version and after I did the workers seems to run well with this setup: - Celery 5.2.7 - Eventlet 0.33 Lastly, I've tried running gevent like so for comparison: celery -A myApp worker … -
I can not deploy my django project to heroku server when I want to deploy in it gives me error
I can not deploy my Django project to the Heroku server when I want to deploy it gives me the error I deploy it with Heroku CLI this is the error remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection- failure remote: remote:! Push failed remote: Verifying deployment... remote: remote:! Push rejected to RBclass. remote: To https://git.heroku.com/rbclasss.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/rbclasss.git' -
From postman I am Trying to send multiple zone details in a array like zone = ["zone1","Zone2"] but i am not able to store it in django
Views.py class EmployeeRegistrationViewSet(viewsets.ViewSet): """ API endpoint that allows employee details to be viewed or edited. """ def list(self, request): platform = EmployeeRegistration.objects.all() serializer = EmployeeRegistrationSerializer(platform, many=True) return Response(serializer.data) def create(self, request): api_status = False serializer = EmployeeRegistrationSerializer(data=request.data,many=True) if serializer.is_valid(): api_status = True serializer.save() return Response( { "status": api_status, "errors": serializer.errors, "results": serializer.data, }, status=status.HTTP_201_CREATED if api_status else status.HTTP_400_BAD_REQUEST, ) Url.py router = routers.SimpleRouter() router.register('employee_reg', views.EmployeeRegistrationViewSet, basename='employee_reg') urlpatterns = router.urls modal.py -> note and city is coming from another model.py -> address.modal.py class AddressAbstractModel(BaseAbstractModel): address = models.CharField(max_length=255) pin_code = models.CharField(max_length=10) zone = models.ManyToManyField(Zone) state = models.ForeignKey(State, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) class Meta: abstract = True class Zone(BaseAbstractModel): name = models.CharField(max_length=64) def __str__(self): return self.name Serializer.py class EmployeeRegistrationSerializer(serializers.ModelSerializer): class Meta: model = EmployeeRegistration fields = '__all__' read_only_fields = [ 'is_active', 'soft_delete', 'created_by', 'created_at', 'last_modified_at', 'deactivated_at', ] postman data { "user_type": "Administrator", "code": "123456", "name": "Aashish Giri", "email": "hopeone476@gmail.com", "mobile_no": "9846695452", "alternate_mobile_no": "9846695452", "designation": "sss", "state": 1, "city": 1, "user": 2, "zone": [ "1", "2" ] } I am trying to send data as a array in many-to-many field but I was not able to save data I got error like - "detail": "JSON parse error - Got AttributeError when attempting to … -
Django: How to automatically fill previous users in the user field of a new model that uses OneToOne relation
I have a conventional project that stores users in auth_user django table. Later, I decided to implement a profiles app. The views.py code is below class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) I do makemigrations and migrate. The table is created with empty data, i.e., previous users that exist in auth_user were not populated in the profiles_profile table. How can I populate old data in my new table? Thanks -
How to check when was last time the User logged in?
I would like to update my model if the user did not logged in the day before . @receiver(post_save, sender=user_logged_in) def user_logged_in_streak(sender, instance, *args, **kwargs): if user_logged_in <check if the user logged in yesterday> <NOT SURE WHAT TO DO HERE >: current_streak = UserStatisticStatus.objects.filter(user=instance.user).first().day_streak UserStatisticStatus.objects.update(day_streak=current_streak + 1) ``` -
Django error while saving to database : IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id
I have two models with OneToMany relation between them. personelModel and arizaModel. When I click the save button, I get the following error: "IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id" personelModel saved but arizaModel not saved in database table. I want both models to be saved in database I want help. /my english is not good i am sorry about that/ models.py: from email.policy import default from tabnanny import verbose from django.db import models # Create your models here. class personelModel(models.Model): p_sicil = models.CharField(max_length=8, verbose_name='Personel Sicili') p_isim = models.CharField(max_length=50, verbose_name='Personel Adı') p_bilgisayar_adi = models.CharField(max_length=4, verbose_name='Bilgisayar Adı') p_durum = models.BooleanField(default=True, verbose_name='Personel Durumu') class Meta: verbose_name = "Personel" verbose_name_plural = "Personeller" def __str__(self): return self.p_sicil class arizaModel(models.Model): p_id = models.ForeignKey(personelModel, on_delete=models.CASCADE) a_aciklama = models.CharField(max_length=100, verbose_name='Arıza Açıklama') a_acilma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Açılma Tarihi') a_durum = models.BooleanField(default=True, verbose_name='Arıza Durumu') a_kapanma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Kapanma Tarihi') class Meta: verbose_name = "Arıza" verbose_name_plural = "Arızalar" def __str__(self): return self.a_aciklama views.py from django.shortcuts import render from django.urls import reverse_lazy from kullanici.forms import PersonelBilgileriForm, ArizaBilgileriForm def kullaniciArizaKaydetView(request): form1 = PersonelBilgileriForm(request.POST, prefix='personel_bilgileri') form2 = ArizaBilgileriForm(request.POST, prefix='ariza_bilgileri') if request.method == 'POST': if form1.is_valid() and form2.is_valid(): personel_bilgileri = form1.save() ariza_bilgileri = form2.save() return render(request, 'kullanici.html',{'PersonelBilgileriForm': form1, 'ArizaBilgileriForm': form2}) forms.py from django import … -
Is there a way I can get a list of all the items with balance variable in django
I have created an API that is being called by my react frontend. So the problem is this I have a viewset that shows a list of all customers in the database which works perfectly. I have also created a retrieve method that shows individual customer details and all the orders purchased. In this retrieve method, I have a variable that shows the balance for the customer. My question is, is there a way I can get a List of all customers with a balance that is greater than 0 and lower than 0 Here is my viewset class CustomerViewSet(viewsets.ViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def list(self, request): customer = Customer.objects.all() serializer = CustomerSerializer(customer, many=True, context={"request": request}) response_dict = {"error": False, "message": "All Customers List Data", "data": serializer.data} return Response(response_dict) def create(self, request): try: serializer = CustomerSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Customer Data Stored Successfully"} except: dict_response = {"error": True, "message": "Phone Number Exists In Database, Fill All Fields"} return Response(dict_response) def retrieve(self, request, pk=None): queryset = Customer.objects.all() customer = get_object_or_404(queryset, pk=pk) serializer = CustomerSerializer(customer, context={"request": request}) serializer_data = serializer.data # Accessing All the Orders Details of Current Customer orders_details = Orders.objects.filter(customer_id=serializer_data["id"]).order_by('-id') orders_details_serializers = … -
How to save file in two different directories after uploading a file in Django
I am working in Python Django with version 4.0.4. I have stucked in a situation where I want to save a file in two different directories at the same time when user browse the file and click on upload button. I am already saving the file in one directory, now I want to save the same file in two different directories. Kindly help me to resolve this issue: Here is the code: views.py: def upload(request): if request.method=="POST": uploaded_file = request.FILES['file extension'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) print(upload_file.name) print(upload_file.size) return render(request, 'abc.html') abc.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="xyz"> <button type="submit"> upload file </button> </form> urls.py: from django.conf import settings from django.conf.urls.static import static if setting.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settins.py: MEDIA_ROOT= '/home/abc/directory1/foldername1' MEDIA_URL = 'abc/' #MEDIA_ROOT_1= '/home/abc/directory2/foldername2' #MEDIA_URL_1 = 'abc2/' Here are the methods for which I am saving the file in a single directory, but when I apply the same methods with different objects It doesn't bother the MEDIA_ROOT_1 and doesn't save the file in this directory. It always save the file of the given path in MEDIA_ROOT. Kindly help me to save this file in different directories -
i try to run django project inside google cloud VM instance and i am receiving error ModuleNotFoundError: No module named '_bz2'
my project is working locally fine but when i clone my project from git inside google cloud VM and try to run the project without any database configuration also i am receiving error:ModuleNotFoundError: No module named '_bz2' and it is comming from pandas File "/usr/local/lib/python3.8/bz2.py", line 19, in from _bz2 import BZ2Compressor, BZ2Decompressor ModuleNotFoundError: No module named '_bz2' can any one tell me the solution for it -
Django JavaScript Array
I have the following JS code: data: [40, 60, 30, 65, 60, 95, 90, 100, 96, 120, 105, 134] This represents a curve in a graph on HTML. I want to draw a line (same value 12 times), and this value is brought by Django. The value is 100. I tried the following: in Django: limit = [mylimit for i in range(1,12)] in JS: data: {{ limit }} didn't work. I even tried creating the list manually on Django: limit = f"{limit}, {limit}, ...." and doing this on JS: data: [{{ limit }}] and nothing works. My goal is to take whatever limit I have (aka: 100), and have the following JavaScript: data: [100, 100, 100..... -
How to write the json for patch on Django REST Framework
I have PATCH button form on ModelViewSet class CompanyViewSet(viewsets.ModelViewSet): serializer_class = s.CompanySerializer queryset = m.Company.objects.all() def patch(self, request, id, format=None): print(id) Now I try to modify the existing data id = 1 So I write this in textarea and push PATCH button. { "id":1, "name": "" } However , there comes error like patch() missing 1 required positional argument: 'id' Maybe my json is wrong?? How can I do PATCH? patch() missing 1 required positional argument: 'id' -
Axios giving 401 (Unauthorized). I am trying to get userdata through react frontend passed to DRF Social Oauth2. Same is working on POSTMAN
Below are the two files LoginScreen.JS which has a submit handler that submits the input. Here we import the axios instance from login.JS. I have also attached the same working example from PostMan. Below are the two files LoginScreen.JS which has a submit handler that submits the input. Here we import the axios instance from login.JS. I have also attached the same working example from PostMan. login.js const baseURL='http://127.0.0.1:8000/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { 'Content-Type': 'application/json', accept: 'application/json' }, }); export default axiosInstance LoginScreen.js const submitHandler = (e) => { e.preventDefault() axiosInstance .post(`auth/token/`,{ username: email, password: password, grant_type: 'password', client_id: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz', client_secret: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz' }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); }); }; -
generating tokens and sending them to users
I am trying to implement the account activation and password reset functionalities and I would like to review the theory. I currently have 2 tables, user and token table. The user signs up. I save the user in the db, generate token and send it via email. So here's how I am tackling the problem: I am creating a 16bytes token and using this to create the link e.ghttp://localhost:1200/api/activation/<token>. However, in the db I am storing the hashed token (hashed with sha256). Then, theoretically, when the user clicks on the link, I perform sha256 on the token and see if it matches with the one stored in the database, right? I think the reason it is recommended to store the hash inside the db is because if the attacker has access to the db, he cannot impersonate the user (it still needs the original token), right?