Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I changed the class name in document via "getElementById" but it doesn't take effect [duplicate]
Thank you for advance. I changed the class name in JavaScript, but it doesn't change. [javascript] for (i = 0; i < storeBtns.length; i++) { storeBtns[i].addEventListener('click', function(){ document.getElementById(this.dataset.product).class = 'btn-primary'})} When I check (document.getElementById(this.dataset.product).class by adding alert to the bottom line, "btn-primary" appears, but this does not apply in the page. What should I do? I also tried with classList.add , but it didn't work, so I was wondering if there is anything else to do, such as returning document . Thank you. -
Django rest framework: Mixed content
I am quite new in Django rest framework. I have a project which contain Django restframework API inside a Django site project(with simple frontend code) and it works fine in my local environment. However in the production domain(HTTPS) it shows as below: Mixed Content: The page at 'https://<my production domain>/audience/labeling_jobs/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://<my production domain>/audience/labeling_jobs/api/jobs/?page=2'. This request has been blocked; the content must be served over HTTPS. I have setup the configuration about SSL/HTTPS according to Django document SSL/HTTPS beforehand but it still got this error. USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_SSL_REDIRECT = True It seems that the Django rest cannot get the correct HTTPS, but it works fine with other django paths, they can be showed on the production page. Is there anything I have missed? -
How to call an API constantly with a function?
I have a customer management system. I am using an API to get all of the customers. It works perfectly. I am using an ID, if there is no customer who has this ID, then it creates a new customer. Here is my code for that: def handle_get_customers(company): customer_service = requests.get(settings.API_ADDRESS + "customer/get/all", headers={'Authorization': "Bearer " + token_key}).json() service_customers = [] for customer in customer_service["data"]: service_customers.append(customer) for person in service_customers: new_customer, obj = Customer.objects.get_or_create(api_id=person["id"]) new_customer.customer_name = person["name"] country, d = Country.objects.get_or_create(country_name=person["countryName"]) new_customer.country = country new_customer.address = person["fullAddress"] new_customer.phone_number = person["phoneNumber"] new_customer.email_address = person["email"] new_customer.currency_choice = person["currency"] new_customer.api_id = person["id"] new_customer.company = company new_customer.save() return service_customers And I am listing all customers on a page. It has a basic listing function like; def customer_list(request): current_user = request.user handle_get_customers(current_user.company) customer_list = Customer.objects.filter(company=current_user.company) context = { 'customer_list': customer_list, } return render(request, 'customer_list.html', context) I want to get all new companies without refreshing the page. I don't know if I can use Ajax for that but I guess the handle_get_customers function should work constantly but I cannot figure out how can I do it? -
Django set value of ForeignKey field in ModelForm upon submission
I have RequisitionModel that takes siteID from my User model as its ForeignKey. How do I have RequisitionModelForm pull the current user's siteID and pass it into the form? *I do not want the HTML template to display the siteID field, but have it set in the "background" upon form submission. forms.py class RequisitionModelForm(forms.ModelForm): class Meta: model = MaterialRequisition fields = ( 'reqDescription', 'reqDateNeeded', 'reqItems' ) widgets = { 'reqDateNeeded': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): super(RequisitionModelForm, self).__init__(*args, **kwargs) queryset=Item.objects.all(), widget=forms.CheckboxSelectMultiple, ) models.py class MaterialRequisition(models.Model): req = models.AutoField(primary_key=True) #change to UUIDField if needed site = models.ForeignKey("project_site.Site", related_name='destinationSite', on_delete=models.CASCADE) reqDescription = models.CharField(max_length=1000, blank=True) reqDateSubmitted = models.DateTimeField(auto_now=True) reqDateNeeded = models.DateField(auto_now=False) reqItems = models.ManyToManyField( Item, through="MaterialRequisitionItems", through_fields=('reqID', 'itemID'), related_name="mat_req_items" ) -
How to show foregin key of another django model in django admin fields or django admin fieldsets
I have two Django models: Bot and Seller. class Bot (models.Model): nick_name = models.CharField (verbose_name="Nick Name", max_length=100) wallet_coins = models.CharField (verbose_name="Bot Coins", max_length=30, default="0") wallet_coins_initial = models.CharField (verbose_name="Initial Coins", max_length=30, default="0") order_amount = models.CharField (verbose_name="Order Amount", max_length=30, default="0") ## it's obtained from sum of initial-coins and order-amount: final_coins = models.CharField (verbose_name="Final Coins", max_length=30, default="0") class Seller (models.Model): bot = models.ForeignKey ('Bot', on_delete=models.CASCADE, verbose_name="Bot Name", blank=True, null=True) market = models.ManyToManyField ('MarketTransfer', verbose_name="Market Card(s)") name = models.CharField (verbose_name="Seller Name", max_length=100) price_ratio = models.CharField (verbose_name="Price Ratio", max_length=10, default="1.5") emulate_final_coins = models.CharField ( verbose_name="Emulated Final Coins", max_length=30, default="0") When i want to use fields or fieldsets property to change the order of fields, i see error below: Picture of Error: https://imgur.com/a/HxgcN24 FieldError at /admin/ea_app/seller/1/change/ Unknown field(s) (show_bot_name) specified for Seller. Check fields/fieldsets/exclude attributes of class SellerAdmin. I want to change the location of fields in Django Admin. codes below works without problem. but i need to change the locations. unfortunately i see error (picture above). class SellerAdminInLine (admin.TabularInline): model = Seller.market.through verbose_name = "In-Use Cards" verbose_name_plural = "In-Use Cards" class SellerAdmin (admin.ModelAdmin): readonly_fields = ['total_price', 'show_bot_coins', 'show_bot_final_coins', 'emulate_final_coins'] list_per_page = 10 list_display_links = ['name'] list_display = ['name', 'wallet_coins', 'price_ratio', 'show_bot_name', 'show_bot_coins', 'added_at'] search_fields = … -
Django - AWS Elastic beanstalk- I was following the Aws documentation - Error: $ eb --version bash: eb: command not found
I was following the AWS documentation, have done - pip install awsebcli in gitbash when I checked for version (eb --version) it has thrown me the error - bash: eb: command not found what should I do - is that a path error - if so how should I correct it?? I appreciate your help -
Django orm foreignkey get latest data
reference class Model1(model.Model): master = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) class Model2(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) How to get latest model2 data I want to have response{ master="USER1", member="USER2", status=0, last_content="latest Model2 text" last_date="2020.03.21" } Is there any better way instead of subquery? -
Heroku ModuleNoteFoundError with django-qr-code
I am currently working on the Backend of my small application. During deployment, I am getting the following error: ModuleNotFoundError: No module named 'qr_code' I am not using the pypi qrcode library, instead I am using the django-qr-code library https://django-qr-code.readthedocs.io/en/latest/pages/README.html My Requirements.txt > asgiref==3.5.0 backports.entry-points-selectable==1.1.1 certifi==2021.10.8 distlib==0.3.4 dj-database-url==0.5.0 Django==4.0.3 django-heroku==0.0.0 django-qr-code==3.0.0 filelock==3.4.0 gunicorn==20.1.0 Pillow==9.0.1 pipenv==2021.11.23 platformdirs==2.4.0 segno==1.4.1 six==1.16.0 sqlparse==0.4.2 virtualenv==20.10.0 virtualenv-clone==0.5.7 whitenoise==6.0.0 My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sessions', 'sendqr', 'qr_code', ] Somehow Heroku can't seem to properly find the django-qr-code library even though it is inside of my requirements.txt. Is there a way to maybe manually push it onto the heroku server or something? -
New clients cannot connect to Django site when site are being used by other clients
We have a Django based web application that is being deployed with Apache and mod_wsgi. The users logs in and can start some CPU-bound processes that can take up to 1-2 minutes. Our problem is, when these CPU-bound processes are being run, the new clients cannot even load the site. Even if they can load it and enter their credentials and press log in button, the site is not opening before the ongoing processes are completed. DEBUG option is False in deployment environment. We are not using django.contrib.staticfiles serve() function to serve our static files. How can I find the reason behind this delay? I suspect that this happens because static content are not being served with a different server? How can I make sure that this is the problem? If that is the problem, can serving the static files with a different virtual host solve the issue? Due to company policy, I cannot share the code directly here. However please let me know if there is any other information I need to elaborate. Thanks for your time and attention in advance. -
django-import-export does not export child class
I wanted to export the parent class of the models alongside with related child class included, but after exporting csv file, only data from parent class is present except for child class. I'm not sure what did I do wrong. class Membership(models.Model): name = models.CharField(max_length=128) email = models.EmailField() class References(models.Model): member = models.ForeignKey('Membership', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=128, blank=True, null=True) contact_details = models.CharField(max_length=128, blank=True, null=True) here's my resources.py class MemberResources(resources.ModelResources): reference_name = Field(attribute='name', widget=ForeignKeyWidget(References, 'name') class Meta: model = Membership admin.py class MembershipAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = MemberResources admin.site.register(Member, MembershipAdmin) I attempted using ForeignKeyWidget but the reference_name is still blank even theres data inside the instance -
Python Django | POST method with nested object. NOT NULL constraint failed
My point is to implement the post method with a nested object which has just ID. When I use all fields of a nested object post method works fine. But I'd like to pass just one field and it is ID, other fields gotta be unrequired Now I'm getting the error like NOT NULL constraint failed: article_article.author_id models.py class Author(models.Model): first_name = models.CharField(max_length=20, blank=True, null=True) last_name = models.CharField(max_length=20, blank=True, null=True) nickname = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.nickname class Article(models.Model): title = models.CharField(max_length=120, unique=True) description = models.TextField(blank=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='articles') created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.title views.py class ArticleView(APIView): def get(self, request, pk=None): if pk: article = Article.objects.get(pk=pk) serializer = ArticleSerializer(article, many=False) else: articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) def post(self, request): data = request.data serializer = ArticleSerializer(data=data) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '' created successfully".format(article_saved.title)}, status=status.HTTP_201_CREATED) serializers.py class AuthorSerializer(serializers.Serializer): first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) nickname = serializers.CharField(required=False) class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=120) description = serializers.CharField() author = AuthorSerializer(required=False) def create(self, validated_data): author_data = validated_data.pop('author', None) if author_data: author = Author.objects.get_or_create(**author_data)[0] validated_data['author'] = author return Article.objects.create(**validated_data) -
How I implement webscoket in django Anyone knows about Websocket implementation in Django rest Framework or Django?
#routing.py re_path(r'sock/WebsocketDjangoRest/(?P<room_name>\w+)/', consumers.WebsocketDjangoRest.as_asgi()), #consumer.py class WebsocketDjangoRest(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) This is a code that Django channels provide us. I am using postman and now i have to check both consumer are connected with the same room name and send message to the each other. Everything is working fine. so when i send a message to the other end it not send and disconnect the websocket. I want to send messsage to the other end in postman and he can as well with the same room name. Here are some images u can see that NOw i have to send message from one to other and receiev that message and vice versa -
No module named 'templates'
Need Help!!! I am learning tag. I got the following response after running. "django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'templates.my_tags': No module named 'templates'" Django version: 3.2.7 my_tags.py from django import template register = template.Library() @register.simple_tag def mul(v1, v2, v3): index.html {% load my_tags %} setting.py TEMPLATES = [{"libraries":{'my_tags':'templates.my_tags'}] -
What is the best way to query and send position of the celery task in queue over an api or websocket
Currently on my project I am trying to get a task running which updates contionusly the number of tasks in queue before that respective task, so the approach I am using is to call a celery task(processingTask) which does the actual processing work inside another celery task(queueUpdatingTask)(which sends a message over websocket about the queue status) So i am trying something like below, /tasks.py @shared_task def sample(): time.sleep(10) return "Dummy task" @shared_task def processingTask(): # some processing @shared_task def queueUpdatingTask(): print("***** Started task trigger and monitor *****") channel_layer = get_channel_layer() loop = asyncio.new_event_loop() new_task = processingTask.apply_async(args=[], kwargs={}, queue='default') # Send update message if the task has entered execution while True: # Break if the task is completed if new_task.ready() and new_task.state == "SUCCESS": send_channel_message_update( channel_layer, loop, new_task.id, f"{new_task.result}", receiver_type="update_status", job_title="Queue Status" ) print("***** Finished task trigger and monitor *****") break # Break if the task is started elif new_task.state == "STARTED": send_channel_message_update( channel_layer, loop, new_task.id, f"{new_task.state}", receiver_type="update_status", job_title="Queue Status" ) print("***** Started task trigger and monitor *****") break # Send update message if the task is still in the queue elif new_task.state == "PENDING": s, i = get_running_tasks(new_task.id) send_channel_message_update( channel_layer, loop, new_task.id, f"{s}", receiver_type="update_status", job_title="Queue Status" ) print("***** In progress … -
Why my queryset filter for creating electricity bill is not working?
I was working on a project in which a user creates some members(model) and their electricity bills (this is also a model) but when I'm applying queryset to ElectricityForm it's showing errors. KeyError at /bills/electricity/create/ my members/models.py from django.db import models import uuid from django.contrib.auth import get_user_model from phonenumber_field.modelfields import PhoneNumberField class Member(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,related_name="members") name = models.CharField(max_length=250) email_address = models.EmailField(max_length=252, null=False, blank=False, unique=True) phone_no = PhoneNumberField() def __str__(self): return str(self.id) my electricity_bills/models.py from django.db import models from members.models import Member import uuid import datetime class ElectricityBill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name="electricity_bills" ) id_member = models.CharField(max_length=40) k_no = models.CharField(max_length=40) last_date = models.DateField() state = models.CharField(max_length=50, null=False, blank=False , choices=state_choices, default="Rajasthan") month = models.CharField(choices=months, default="January", max_length=10) year = models.CharField(choices=years, default="2022", max_length=4) amount = models.PositiveIntegerField() email_send = models.BooleanField(default=True) is_email_sent = models.BooleanField(default=False) def __str__(self): return str(self.member) my electricity_bill/views.py class ElectricityBillCreateView(LoginRequiredMixin, CreateView): model = ElectricityBill template_name = 'bills/electricity/bill_create.html' form_class = ElectricityForm success_url = reverse_lazy('ebills_list') my electricity_bills/forms.py from django import forms from .models import ElectricityBill from members.models import Member from django.contrib.auth import get_user_model class ElectricityForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ElectricityForm, self).__init__(*args, **kwargs) self.fields['member'].queryset = Member.objects.filter( created_by=self.request.user) member = forms.ModelChoiceField(queryset=Member.objects.all()) k_no … -
How to set password show/hide eye button in Django form?
How to set password show/hide eye button in Django form Well I know same question is their but solution not working for me Is their a second way or fixed way of this This also can be version issue bcz this question was asked 2-3 years ago... -
Architecture for setting up Constants and using them in Django
Currently my project has over more than 500 constants, currently we are storing them inside individual modules files but it is becoming difficult to manage them . We have have thought of using DB and cache to store these constants but not sure about the performance. Can someone please suggest a better architecture or if someone has already used DB to store constants please let me know the better way. There are several types of constants in the code also keep in mind while answering that I am looking solution for Django. -
Django show error : "name 'dif_months_without_date' is not defined" though defined
I make the first django app and get error: NameError: name 'get_date' is not defined My structure: app person views.py models.py my_core common.py In common.py, i defined def get_date(): return "something" When i call get_date() def in views.py, it is ok, but call it in models.py it show error. In both views.py and models.py imported : from my_core.common import * What am i missing? -
How to allow a Channels consumer to access session generated by HTTP requests?
I have a project that used to run under WSGI, and I recently configured it to ASGI. It included code from back then, such as the following function that processes a login request: def authenticate(req): ... try: query = models.User.objects.get(...) req.session['user'] = query.id #Login successful ... except: #No record, reject request ... What I want to do now is to create a WebsocketConsumer and access the session from within. I have enabled SessionMiddlewareStack. The problem is that the consumer does not even see the session because the session's ID is not attached to the WebSocket request as a header. Is there a way to allow it to access the data? class SpaceConsumer(WebsocketConsumer): def connect(self): #Session object is empty, while HTTP requests see it as populated with the user's ID if 'user' in self.scope['session']: self.accept() #Only allow authenticated user Information online is scarce, and most are written for older versions of Channels. I am using Channels v3. -
Docker container runs on VM but not on Cloud Run
I have a Django container and normally I am running it on a VM. But i tried to cloud run to run that image. However when I tried that I got the below error. Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Which is weird. And then I tried to create a virtual env in Dockerfile. Maybe cloud run was overwriting PATH or something. It worked. I need to create it without virtual env. What could be the reason? -
Not able to show custom errors after form sbmission in django
I am trying to show errors that I receive besides the fields but the errors are not showing in the template. models.py -
javascript/ajax not working when add two product to cart, how to solve this?
On my cart view page, I can increase and decrease product quantity by clicking + and - button when the cart has one product. When I add more than one product to my cart increase and decrease button does not work at any product. Working Fine when only one product is in my cart. When adding more than one product to the cart increase(+) and decrease(-) button doesn't work. HTML {% for cart_product in cart %} <tr class="product-row"> <td> <figure class="product-image-container"> <a href="{{ cart_product.product.get_absolute_url }}" class="product-image"> <img src="{{ cart_product.product.product_img_1.url }}" alt="product" class="img-fluid"> </a> </figure> </td> <td> <div class="product-single-qty"> <div class="input-group bootstrap-touchspin bootstrap-touchspin-injected"> <div class="minus-cart value-button" value="Decrease Value" pid="{{ cart_product.product.id }}">-</div> <span class="number">{{ cart_product.quantity }}</span> <div class="plus-cart value-button" value="Increase Value" pid="{{ cart_product.product.id }}">+</div> </div> </div> </td> <td class="text-right"> <span class="subtotal-price each_pro_subtotal">{{ cart_product.total_cost }}</span> </td> </tr> {% endfor %} javascript $(".plus-cart").click(function(){ var id = $(this).attr("pid").toString(); var eml = this.parentNode.children[1]; $.ajax({ type : "GET", url : "/shop/pluscart", data : { prod_id : id }, success : function(data){ eml.innerText = data.quantity; each_subtotal = document.getElementsByClassName("each_pro_subtotal"); each_subtotal[0].innerText = data.each_pro_subtotal; document.getElementById("subtotal").innerText = data.subtotal; }, }) }); -
The text entered in the title field is entered in the same slug, but I do not know why;
I am creating a post on the superuser page, and suddenly slugfield is automatically entered. The text entered in the title field is entered in the same slug, but I do not know why; Why is the slug automatically entered as the text entered in the title? class POST(models.Model): slug = models.SlugField( unique = True, allow_unicode = True, ) title = models.CharField(max_length = 30, default = '') -
How to access Python dictionary in Javascript Script in Django
I am working in Django, where I am sending a Python Dictionary into an HTML file. In that HTML File, I want to access the Python dictionary and append the keys and values of dictionary into the Javascript arrays. I am able to access Python dictionary in HTML, but can't do the same in Javascript. This is how I am able to access the values of Dictionary in HTML, {% for key, image in predictedLabel.items %} <tr> <th scope="row">{{ key }}</th> <td>{{ image }}</td> </tr> {%endfor%} The Javascript script that I have is of Pie Chart, which is as given below, <script> var xArray = []; var yArray = []; var xArray = ["Italy", "France", "Spain", "USA", "Argentina"]; var yArray = [55, 49, 44, 24, 15]; var layout = { title: "Distribution of Labels" }; var data = [{ labels: xArray, values: yArray, hole: .5, type: "pie" }]; Plotly.newPlot("myPlot", data, layout); </script> I want to put the Python Dictionary Key into the xArray and the Values of Dictionary into the yArray. For that, I need to access the Python Dictionary in the Javascript script, but I do not know how to access the Python values in the Javascript script. Can … -
Django filer change unsorted uploads
I'm using django-filer now and by default, every image will be stored in "Unsorted Uploads". How can I change that folder? The question is similar to this Using django-filer, can I chose the folder that images go into, from 'Unsorted Uploads'. But I want to know is there any better way to do this?