Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery / AJAX - Async view - eventlisteners not responding and .remove() is not respecting the selection
it is my first time writing JQuery/AJAX and (silly me) I'm tryng to do something quite complex actually (or at least it is for me lol). Basically I am making an infinte carousel. I am sending the paginated data through a Django view, and I am using JQuery to load it asycronously (so to not refresh the page continuously and lose the previous content). This is the relevant code (I am not including any django related code, because everything there is working just fine, the issue is in the HTML/JS. However if you want to take a look at it, just let me know) HTML <main> <div id="outside-container"> <div id="inside-container" class="infinite-container"> {% for city in cities %} {% get_weather city.name 'metric' 'it' as weather_info %} <div class="items"> <div class="data-div"> <ul> <li><b>{% destructure weather_info 'location' 'city' %}</b> </li> <li class="weather">{% destructure weather_info 'weather' 'description' %}</li> <img src="{% destructure weather_info 'weather' 'icon' %}"> <li>{% destructure weather_info 'main' 'temperature' %}</li> <li>{% destructure weather_info 'location' 'time'%}</li> </ul> </div> <img loading="lazy" class="carousel-img" src="{{city.image.url}}"> </div> {% endfor %} </div> </div> <div id="directions"> <a id="right-button">Right</a> <a id="next-slide" href="?page=2">Next</a> </div> </main> CSS body { margin: 0; padding: 0; background: linear-gradient(-45deg, #4699f8, #fff2f7, #23a6d5, #1779e9); background-size: 400% 400%; animation: … -
Why my map is not displaying using django API in html?
I am using Django API and my map is not displaying. enter image description here -
multiple arguments in logger and use them in formater - django
I want to send multiple arguments in logger messages and use them directly in formater. For example, logger.exception('Exception message, 'arg1', 'arg2') logger.warning('warning message, 'arg1', 'arg2') And in formater. I want to use args like '[%(asctime)s] %(levelname)s|%(name)s|0|0|%(message)s|%(args1)s|%(args2)s' I don't want to use *args and **kwargs for these arguments. Is there any way to implement this? Any help would be appreciated. -
Infinitely posting data to server problem with using fetch POST in JavaScript
I am a university student and this is my first time of putting all together of server, api and client sides. My problem is that first I have created an API using Django-Rest framework. When I post data to that server using fetch function in JavaScript, it keeps posting that data and does not stop until I close. In the server database, many same data have been created. I cannot figure out how to fix it. My intention was I want to post the data just once. Please help me how to do it. Thank you. -
Integrate PHP auth in Django Project
I have a PHP build authentication service for my users now I want to integrate the same authentication that I have in PHP into my Django project, Is it possible, if yes can you provide me with some material where I can read about this? or is it possible I run PHP files for authentication in my Django project rather than using Django build-in authentication? -
How to resolve AssertionError: .accepted_renderer not set on Response in Django Rest Framwork
While I am calling Django url, I get an error: AssertionError: .accepted_renderer not set on Response. My code is: from rest_framework.response import Response from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from myapp.models import employees from .serializers import EmployeeSerializer @api_view(('GET',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def getData(request): employees = {'name':'Bill', 'location':'Kolkata' } return Response(employees) def getEmployees(request): employee_list = employees.objects.all() serializer = EmployeeSerializer(employee_list, many = True) return Response(serializer.data) -
How to set deafult value of django form select field in template?
How to set deafult value of django form select field in template? How to set deafult value of django form select field in template? -
Trying to kill process with root user but it says: <kill: (15307): Permission denied>
I have a shell file <save_intraday.sh> that contains docker-compose exec web python manage.py save_retail_trades_data After executing this python script import subprocess subprocess.run('./save_intraday.sh', shell=True) some django command in docker container starts running and every things works perfectly. After some time i capture every task pid that is related to command above with ps aux | grep save_retail then im executing sudo kill -9 <captured pid> The problem is after exeuting sudo kill -9 <captured pid> it says kill: (15307): Permission denied (of course 15307 is for demo). As long as i know root user is the most privileged user but its says permmission denied... I will appreciate if you help me to solve this problem I'm trying to kill task with pid with sudo kill -9 <pid> and i expect to not show me permission denied and kill the proccess -
How to initialize value of foreign key in Django form
Im trying to initialize a model form where both fields are foreign key. Model: class Subcohort(models.Model): cohort_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subcohortid') parent_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subparentid') Form: class SubcohortForm(forms.ModelForm): class Meta: model = Subcohort fields = [ "cohort_id","parent_id", ] Views: cohortidnew = Cohort.objects.latest('id').id initialvalue2={ 'cohort_id':int(cohortidnew), 'parent_id':id, } form2 = SubcohortForm(initialvalue2) if form2.is_valid(): return redirect('/dashboard') It is saying my form is not valid. Can someone explain what is the reason behind this and how to fix this? Thanks. -
Identify which exception to raise in Django Storage
I have extended the Django Storage class to integrate the on demand virus scanning. I have to raise an exception if the uploaded file contains a virus. User can upload file from Django Admin or from API interface (Django Rest Framework). I need to raise an Django Rest Framework APIException if the user upload the file using API or need to raise a Django Exception if the user upload the file from Django Admin. Is there any way to identify how the user upload the file before raise the Exception? Thanks in advance. Please find the below mentioned code snippet. # Storage.save() def save(self, name, content, max_length=None): """ Integrate clamd for scanning. """ cd = clamd.ClamdUnixSocket() try: scan_results = cd.instream(content) if scan_results['stream'][0] == 'FOUND': # I need to identify the source of the request before raise the exception return super().save(name, content, max_length) except clamd.BufferTooLongError: return logger.warning("Input file's buffer value is exceeding the allow limit.") except clamd.ConnectionError: return logger.warning("ClamAV connection cannot be established.") -
In Django trying to add images with forms
The problem is in the image field. I can't add an image though I used the image field. I want to add an image to the form. please see the pic. -
Django -> 'WSGIRequest' object has no attribute 'data' -> Error in json.loads(request.data)
I saw a similar question but the answer is rather vague. I created a function based view for updateItem. I am trying to get json data to load based on my request. but am getting the error -> object has no attribute 'data' Views.py file: def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print("productID", productId, "action", action) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer,complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse("Item was added!", safe=False) JS File: function updateUserOrder(productId, action) { console.log('User is logged in...'); let url = '/update_item/'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ productId: productId, action: action }), }) .then((res) => { return res.json(); }) .then((data) => { console.log('data', data); }); } urls python file: urlpatterns = [ path("",views.store,name="store"), path("cart/",views.cart,name="cart"), path("checkout/",views.checkout,name="checkout"), path("update_item/",views.updateItem,name="update_item"), ] The Error seems to also occur in my fetch function in the JS file. With my method POST. Can't find a solution, what am I doing wrong here? -
Django Rest hash existing non hashed passwords
I have an existing database with non hashed plain text passwords which I want to convert to hashed passwords in Django Rest Framework. I have tried the following but it is not working, as in while the hashing is done I am unable to login when this password is hashed Try 1 queryset = CustomUser.objects.all() for item in queryset: item.password = make_password(item.password) item.save() return Response({"message": "done"}) Try 2 queryset = CustomUser.objects.all() for item in queryset: item.set_password(item.password) item.save() return Response({"message": "done"}) -
Multiple Image upload in django rest framework
How to upload multiple images in DRF. I'm getting all the list of images while looping through it, but it only saves the last one. I want to save all the image and show it in response. Do I have to create separate serializer for Multiple Image serialization? #models class ReviewRatings(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product.product_name class ReviewImages(models.Model): review = models.ForeignKey(ReviewRatings, on_delete=models.CASCADE, related_name='review_images', null=True, blank=True) images = models.ImageField(upload_to='reviews/review-images', null=True, blank=True) def __str__(self): return str(self.images) #Serilaizer class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" #Views class SubmitReview(APIView): permission_classes = [IsAuthenticated] def post(self, request, product_slug): data = request.data if data["rating"] == "" and data["review"] == "": review = ReviewRatings.objects.create( user=request.user, product=product, rating=data["rating"], review=data["review"], ) review_images =request.FILES.getlist('review_images') rev = ReviewImages() for image in review_images: rev.review=review rev.images = image rev.save() serializer = ReviewSerializer(review, context={'request':request}) return Response(serializer.data, status=status.HTTP_201_CREATED) #Postman Response I get on the current implementation { "user": "Jackson Patrick Gomez", "rating": 4.8, … -
How to send the content of html to another html
I would like to fill out a form on an html page and then send the completed form to another html to check the entries there and then save them. I just don't know how to send the data from one html to another. I ask you to help me. Thanks question.html here is the form {% extends 'dependencies.html' %} {% block content %} <div class="jumbotron container row"> <div class="col-md-6"> <h1>Add Question</h1> <div class="card card-body"> <form action="" method="POST" id="form"> {% csrf_token %} {{form.as_p}} <br> <input type="submit" name="Submit"> </form> </div> </div> </div> {% endblock %} approve_questions.html I wanna to get the content from question.html here currently empty views.py def questions(request): form = addQuestionform() if (request.method == 'POST'): form = addQuestionform(request.POST) if (form.is_valid()): form.save(commit=False) html = render_to_string("notification_email.html") send_mail('The contact form subject', 'This is the message', 'noreply@codewithstein.com', ['example@gmail.com'], html_message=html) return redirect("login") context = {'form': form} return render(request, 'addQuestion.html', context) def approve_questions(request): return render(request, "approve_question.html") -
django rest_framework when creating object says get() returned more than one Request -- it returned 2
I'm creating a api where everytime someone request for repairs it also saves in inspection table when I try to post in postman { "reqdescription": "test", "techofficeid": "ICT" } this is the row of request |reqid|reqdescription|reqdate|officerequestor|techofficeid| | 36 | test |2022...| HR | ICT | while this is the row of inspection |inspectid|reqid| etc...| description | | 5 | 36 |.......|Request object (36)| instead of test why it's Request object (36) this is my signals.py @receiver(post_save, sender=Request) def create_transaction_log(sender, instance, created, **kwargs): if created: Inspection.objects.create(reqid=Request.objects.get(reqid=instance.reqid), description=Request.objects.get(reqdescription=instance.reqdescription), reqdate=str(datetime.now().strftime('%Y-%m-%d'))) my assumptions is because of OneToOneField but maybe I was wrong Hope someone can help models.py class Inspection(models.Model): inspectid = models.AutoField(primary_key=True) reqid = models.OneToOneField('Request', models.DO_NOTHING, db_column='reqid', blank=True, null=True) insdate = models.DateField(blank=True, null=True) diagnosis = models.CharField(max_length=100, blank=True, null=True) inspector = models.ForeignKey('Technician', models.DO_NOTHING, db_column='inspector', blank=True, null=True) isinspected = models.BooleanField(default='False', blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) reqdate = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'inspection' class Request(models.Model): reqid = models.AutoField(primary_key=True) reqdescription = models.CharField(max_length=100, blank=True, null=True) reqdate = models.DateField(auto_now_add = True, blank=True, null=True) officerequestor = models.ForeignKey('Office', models.DO_NOTHING, db_column='officerequestor', blank=True, null=True) techofficeid = models.ForeignKey('Technicianoffice', models.DO_NOTHING, db_column='techofficeid', blank=True, null=True) class Meta: managed = False db_table = 'request' -
Using Ajax to pass a variable to django views.py
I am trying to use ajax pass a variable "arr" from my calender.html to my views.py file. For testing purposes, I'm returning a HttpResponse for whatever "arr" is. In this case, it is "1" however instead of passing "1", I'm getting "None". I'm unsure of why nothing is being sent. calender.html This is what I have for my calendar function in views.py Output This is what I have for my url.py if its relevant at all I'm pretty new to ajax and still learning Django so if anyone can help, I would really appreciate it. (btw I know calendar is spelled wrong, it wasn't my doing) -
Mass updating (including removal) of a many-to-many relationship django
I have a Django app with two models linked by a many-to-many relationship. Service, problem_type. A service provides assistance for a number of problem types. I use the problem_type table to later facilitate lookups of all services that help for a specific problem type. I update my model from an external API. I take in a list of "problem_types" for each service, eg: ['housing', 'financial aid' ... etc] Over time, a service might get new problem_types or remove old ones. Is there a best practice for managing this? Adding new problem_types relationships or new problem_types is ok, I just loop through the incoming list of problem types and add any new ones to the problem_type relationship/table, but what is the best way to remove now redundant ones? Is it best to: Loop through associated problem types and delete each not in the new incoming list? Get all associated problem types and delete every relationship before re-adding the incoming list Is there some built-in method for doing this that I have not been able to find? In an ideal world love to be able to pass the incoming list of new problem_types with the current set of related problem_types to a … -
import environ could not be resolved pylance when using venv
I'm new in Python/Django and I'm trying to create a live app. I did create the django project first, then realized I should do this in a venv. So I created the venv within my project folder. I managed to get my PostgresQL db connected, and since I'm trying to keep my stuff secure, I'm storing my DB password in a global variable. import environ from pathlib import Path env = environ.Env() environ.Env.read_env() My problem is that I keep getting the error "import environ could not be resolved pylance" in my settings.py file and I've no idea why. I think I've set up my venv correctly and placed it in my project folder. Is something wrong with my interpreter? I'd really like some help with this please. this is how my files are laid out [this is the error i'm seeingI seem to be inside my venv and i'm able to run my app just fine and update my database no problems. which I'm thinking shouldn't work if there really is an issue with how my venv is setup?](https://i.stack.imgur.com/lk2Dn.png) I've tried everything I can think of. Made another venv and played around with it. Only thing I'm stuck on is … -
Django: Selenium multiple drivers (windows)
I'm creating API that is based on web-scraping via Selenium. And I've just figured out that: if user1 makes request, as long as he's waiting for response (selenium is scraping page for needed data) user2 must wait for user's1 chromedriver to stop session and only after that selenium starts scraping data for user2, that's not efficient at all ;(I'm pretty sure it's possible to run multiple drivers at the same time (one driver for each request) just like Django-channels run multiple channels. How can I achieve that? I'M NOT TESTING, I'M SCRAPING WEB-PAGES -
DRF Nested serializers
I'm kind of confused in writing the nested serializer in django rest framework. If I have tow models Account and UserProfile. In which UserProfile is ForeignKey to Account and when writing serilaizer should I call UserProfile Serializer in Account's Serializer or call Account Serilaizer in UserProfile Serializer. #Models.py Class Account (AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True Class USerProfile(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=100) address_line_2 = models.CharField(max_length=100) phone = models.IntegerField(null=True) And in writing serializer I'm confused. So please explain to me in detail how to write nested serializer. #Serializers.py class AccountSerializer(ModelSerializer): class Meta: model = Account fields = ["first_name", "last_name", "email", "password"] extra_kwargs = { "password": {"write_only": True}, } class UserProfileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def create(self, validated_data): #Didn't write the logics here as of now. return super().create(validated_data) So Is this this correct way to write nested serializer? -
process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'
hello every one who helps me? python:3.8 Django==4.0.4 celery==5.2.1 I am using python/Django/celery to do something,when I get data from hive by sql,my celely worker get this error "process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'",and then,my task is not be used to finish and the tcp connect is closing! what can I do for it to solve? I try to do: CELERYD_MAX_TASKS_PER_CHILD = 1 # 单work最多任务使用数 CELERYD_CONCURRENCY = 3 # 单worker最大并发数 CELERYD_MAX_MEMORY_PER_CHILD = 1024*1024*2 # 单任务可占用2G内存 CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24 * 3 -Ofair but these is not using for solving. -
Function trigger other function and ends before result
I'm developing an API with Django Rest Framework for handling some subscriptions I wanted do make the registration in 2 steps. First, i would register user in my database, after that i want to register user to other service (email marketing, for example). I have to do it in two steps because the registering of the user in external services may take some time (or the service can be unavailable at the time of request) and i don't want users to wait everything so they can go to other pages. My idea is: After registering user into my database, i would return http 200_ok to the front-end so user can go to other pages, and in my backend i would use that data to try to register the user in external services as many times as needed (e.g: waiting if other services are unavailable). But rest_framework only allows me to return Response() (i'm using class-based views), so i only can return http 200_ok, but if i return the function ends and my other functions (that will take more time to run) will end aswell. Is there a way to do this? -
Django Multiprocessing Error on Server But Works Fine on Localhost - __init__() got an unexpected keyword argument 'initializer'
When I Run my Django App on my computer it works fine. But when pushed to Ubuntu Server I am now getting the error. __init__() got an unexpected keyword argument 'initializer' Here is my View Code def verifyt(request): listi = get_listi() print("verifyt",listi) with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor: results = executor.map(wallet_verify, listi) return HttpResponse("done") Ive upgraded my python from 3.6.9 to 3.7.5 still same error. -
I want to add 'created_by' and 'modified_by' fields to my Django models, How do I do that?
My custom user model in account.models.py: class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('abc', 'abc'), ('def', 'def'), ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default=None) designation=models.CharField(max_length=70) is_active=models.BooleanField() is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username A model in sample.models.py: class LockData(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE, default=None) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None, blank=True, null=True) lock=models.BooleanField(default=False) date=models.DateField(default=datetime.date.today) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) So, along with created_on and modified_on fields, I also want 'created_by' and 'modified_by' fields. How can I do that?