Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having problem ' Pip install -r requirements.txt ' [closed]
this is my first project with django and python. **working on mac mini m1. visualcode. latest python for mac. ** my friend opened the whole project on other computer (windows) and told me and my teammates to copy the folder, put path of static and then run : Pip install -r requirements.txt although i tried to install everything including xampp and run server and there is a problem when it comes to setup.py uploading the req.txt and the error. enter image description here appdirs==1.4.4 asgiref==3.3.1 astroid==2.4.2 atomicwrites==1.4.0 attrs==20.3.0 autopep8==1.5.4 beautifulsoup4==4.9.3 category-encoders==2.2.2 certifi==2020.12.5 chardet==4.0.0 colorama==0.4.4 cycler==0.10.0 distlib==0.3.1 dj-database-url==0.5.0 Django==2.1.15 django-appconf==1.0.4 django-bootstrap-staticfiles==3.0.0.1 django-bootstrap4==2.3.1 django-chartjs==2.2.1 django-contrib-comments==1.9.2 django-crispy-forms==1.10.0 django-jquery==3.1.0 django-load==1.0.0 django-mysql==3.10.0 django-pandas==0.6.4 django-staticfiles==1.2.1 filelock==3.0.12 future==0.18.2 gunicorn==20.0.4 idna==2.10 importlib-metadata==2.1.1 iniconfig==1.1.1 isort==5.6.4 joblib==1.0.1 kiwisolver==1.3.1 lazy-object-proxy==1.4.3 matplotlib==3.4.2 mccabe==0.6.1 mysql==0.0.2 mysql-connector-python==8.0.22 mysqlclient==2.0.1 numpy==1.19.4 packaging==20.8 pandas==1.1.5 patsy==0.5.1 Pillow==8.3.1 pluggy==0.13.1 protobuf==3.14.0 py==1.10.0 pycodestyle==2.6.0 pydot==1.4.2 pyitlib==0.2.2 pylint==2.6.0 pylint-django==2.3.0 pylint-plugin-utils==0.6 pyparsing==2.4.7 pytest==6.2.1 python-dateutil==2.8.1 python-decouple==3.3 pytz==2020.4 requests==2.25.1 scikit-learn==0.24.2 scipy==1.7.0 six==1.15.0 sklearn==0.0 sklearn2==0.0.13 soupsieve==2.0.1 sqlparse==0.4.1 statsmodels==0.12.2 style==1.1.0 threadpoolctl==2.2.0 toml==0.10.2 typed-ast==1.4.1 Unipath==1.1 update==0.0.1 urllib3==1.26.4 virtualenv==20.2.2 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.4.0 i didnt try anything because i dont know what to do.. expecting to have a solution and understanding the error.. -
How to solve a UnicodeDecodeError in django?
I'm trying to get a run out of my project and this error occurs : * 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Raised during: Blog.views.post_list The string that could not be encoded/decoded was: �� I would really appreciate it if anyone tell me how can I handle this error . here is my model : ` class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .filter(status=Post.Status.PUBLISHED) class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF','Draft' PUBLISHED = 'PB' ,'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey(User,on_delete=models.CASCADE ,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) objects = models.Manager() published = PublishedManager() class Meta: ordering = ['-publish'] indexes = [ models.Index(fields = ['-publish']), ] def __str__(self): return self.title ` here is my view.py ` def post_list(request): posts = Post.published.all() return render(request,'Blog/post/list.html',{'posts':posts}) ` everything in my administration seems to be fine .and I haven't used any wierd characters in my posts . -
Integration of third party authentication on Django Project
I have an authentication system that is built in PHP for my clients to log in using only one login credential to access different products. Mostly my web pages are written in PHP so it is easy to integrate different PHP products with the same authentication. Now I have a Django webpage and want to authenticate my clients with the same authentication system that is written in PHP, is it possible? I have three PHP files which help me with the authentication can I directly tell my Django to use these files for authentication and after success redirect to the webpage to use different features inside the webpage? -
Simultaneously logins from multiple users without using framework in django
We are working on a django project and we want to allow users to be able to access the system simultaneously. However, we are having a problem in scenarios when for example: User1 logs in then User2 logs in next, if User1 did not logout from the system, when User2 refreshes the site, User2 is able to access User1 session. How can we prevent this from happening? Without implementing an API framework. Thank you. We tried to delete the request.session when the user logs out. -
I don't have django_redirect table with migration marked applied though
As I go through django-redirects docs INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.redirects', ] MIDDLEWARE = [ 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ] python manage.py showmigrations redirects [X] 0001_initial [X] 0002_alter_redirect_new_path_help_text Request URL: http://127.0.0.1:8000/admin/redirects/redirect/add/ ERROR saying..... no such table: django_redirect \Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_redirect -
Can I build an app and website blocker using cross-platform Flutter and python?
I wanna build an application in which I can block using a particular installed application or visiting websites where I use flutter for the UI and only Python and Django for the backend. I tried searching online for this and I found that this can only happen with Java. -
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 …