Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VSCode Permission issues for File creation and Renaming in a Django App
I'm having an issue with creating another python file inside of the main app of my Django tree (I'm still learning Django so I'm not sure of the terminology). When I try to create a file inside of main part of the app named tweets I get this error. Unable to write file '/Users/ak/Dev/tweetme/tweets/forms.py' (NoPermissions (FileSystemError): Error: EACCES: permission denied, open Then I said fine, I'll just create the file in another directory and move it to the tweets folder, When I attempt this, I get the following error. Error: EACCES: permission denied, rename '/Users/ak/Dev/tweetme/tweetme/forms.py' -> '/Users/ak/Dev/tweetme/tweets/forms.py' From what I can read only people having this issues have downloaded some SSH shelling mod, which I don't have, nor do I know what that is. This problem came on suddenly, When I started this project I had no problem created files inside of the tweets folder. Does anyone have any insight into this?? Or how I can fix this? -
implementing a multi-filter search in Django
I have a search bar for searching jobs. There are 3 filters namely description, categories and locations. For description, I want to search a job by a company name, job title or job description. Even if the user inputs, "company name and job title", i should retrieve a correct match not exactly but somewhat close. How do I get this? models.py class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_mode = models.CharField(max_length=20, choices=MODE_CHOICES) industry_type = models.CharField(max_length=200) internship_desc = RichTextField() class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) company_name = models.CharField(max_length=100) views.py def user_search_internship(request): if request.method == "POST": internship_desc = request.POST['internship_desc'] //can be title, desc, company or a combo internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] internships = Internship.objects.all() if internship_desc != "" and internship_desc is not None: internships = internships.filter(internship_title__icontains=internship_desc) context = { } return render(request, '', context) -
Django Rest Framework SQL Query CORS
I am building a tool where users can enter certain parameters and when they hit submit, it will query a mssql database and return some data. The data is passed through Django Rest Framework into a React frontend. The database is massive, so some queries might take several minutes to return. The issue I'm having is that for queries that take a long time, in the Network tab the status show CORS error: MissingAllowOriginHeader. The data returns fine for shorter queries, for longer queries after 30-45 seconds of loading I will get the CORS error. Also, note that this only occurs on a production IIS server, and works fine on my local server. I have tried the following in my settings.py already CORS_ALLOW_ALL_ORIGINS = True ACCESS_CONTROL_ALLOW_HEADERS = True How I'm getting the data from the sql server class SearchView(APIView): def post(self, request, *args, **kw): with connections["mssql"].cursor() as cursor: cursor.execute(sql_str) all = cursor.fetchall() How I'm making the request from React axios .post(process.env.REACT_APP_SEARCH, holder, { headers: { Authorization: "JWT " + sessionStorage.getItem("refresh"), "Content-Type": "application/json", }, }) -
Change model value to None in Query set by checking a field value inside it from Manager
I have a Manager fucntion that prefetches cover photo of the model. the cover_photo (Foreign key to CoverPhoto) model has a field is_verified. Is there a way to make the cover_photo object None if it has is_verified=False from the manager? So that from normal user point view I can hide unverified photos but still need other things and from admin side I can see all photos in List get query. return self.prefetch_related( Prefetch( "deity_list", queryset=Deity.objects.select_related("cover_photo") .filter(is_verified=True, site_visible=True), ), )``` -
modulenotfounderror no module named
I need to implement a function in a file where it executes a python script in another folder. python_project . ├── a │ ├── funcs (folder) | | |--->myfunc.py │ └── my_custom_lib.py |--calc.py in calc.py I have the following function: def anotherfunction(func): os.system('python3 a/funcs/myfunc.py') When I execute it, I got an error enter code here *PS: The main application is in Django -
Steps to deploy ajax django rest api app for production
I created a back-end using Django Rest Framework, And a frontend using some html CSS and ajax for api calls, it's working well but now how can I deploy that app for product -
how to send custom message with activation Email in Django Djoser?
After signup request I am getting this Email to activate my account. I m using Djoser framework for user Authentication system. How can I change the message in email but the activation link should remain same. Email: You're receiving this email because you need to finish activation process on localhost:8000. Please go to the following page to activate account: http://localhost:8000/activate/MQ/5r7-28cd6539635652113a77 -
pgAdmin Blocked by Quick Heal Total Antivirus
I am Using Postgres for the first time. So while trying to view the data in my table Quick Heal Blocked it by saying that was a Ransomware. Here is the report(given below): Report for - Total Security Ransomware Protection Friday, 04 June, 2021, Time 23:55:08 Total Security Version - 19.00 Virus database - 04 June 2021 ------------------------------------------------------------------------------------------- Detected: HEUR:Ransom.Win32.InP in D:\PostgreSQL\pgAdmin 4\bin\pgAdmin4.exe Action taken: Quarantined --------------------End of Report---------------------- Why did this happen and how to make everything ok ? -
I can't get the login page after submitting logout, django, "from django.contrib.auth import login, views as auth_views"
https://stackoverflow.com [[from django.urls import path, include from users_app import views from django.contrib.auth import login, views as auth_views urlpatterns = [ path('register/', views.register, name='register'), path('login', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout', auth_views.LoginView.as_view(template_name='logout.html'), name='logout') ] ###Here is my login and logout concept it is in base file {% if user.is_authenticated %} <div class="form-inline my-2 my-lg-0"> <div class="p-2 bg-dark text-white">Logged in as {{ user.username }}</div> <a href="{% url 'logout' %}"> <button class="btn btn-info my-2 my-sm-0" type="submit">Logout</button> </a> </div> {% else %} <a href="{% url 'login' %}"> <button class="btn btn-success mr-2 my-2 my-sm-0" type="submit">Login</button> </a> <a href="{% url 'register' %}"> <button class="btn btn-primary my-2 my-sm-0" type="submit">Register</button> </a> {% endif %} ]1 -
how to connect AWS RDS to ECS FARGATE Container using DJANGO and postgreSQL
Im not sure what is wrong here but iam using django docker-compose postgresql and i am trying to connect the db that I have created using AWS RDS to the ECS Container. Following the instructions on AWS Docs, I have created a role with a policy applied to the task definition using the AWS Secret Manager. Also in the Security Group for RDS, I have given access to the security group of ECS Fargate Container. Now the issue, the task cannot start. They always say pending... then become stopped please find the task traceback below: 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor backend 6/4/2021, 1:47:53 PM return self._cursor() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor backend 6/4/2021, 1:47:53 PM self.ensure_connection() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection backend 6/4/2021, 1:47:53 PM self.connect() backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend 6/4/2021, 1:47:53 PM return func(*args, **kwargs) backend 6/4/2021, 1:47:53 PM File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect backend 6/4/2021, 1:47:53 PM self.connection = self.get_new_connection(conn_params) backend 6/4/2021, … -
Differentiate between an static and a dynamic QR by received data
Right now the frontend side reads a QR that can be static or dynamic and it's sent to the backend (Django). This QR it's sent as a raw data string and I need to differentiate between this string represents a static or dynamic QR. Is there any way to do that? -
Using python-requests with Django's LiveServerTestCase fails with 502
I am attempting to integrate a 3rd party app which uses python-requests to fetch urls it parses from templates. I am trying to use a LiveServerTestCase to test the integration. Oddly, curl works but the requests test test_requests_static_file fails with: requests.exceptions.HTTPError: 502 Server Error: Connection refused for url: http://localhost:35819/static/testapp/style.css Any ideas here? import subprocess import requests from django.contrib.staticfiles.testing import StaticLiveServerTestCase class LiveServerTests(StaticLiveServerTestCase): def test_curl_static_file(self): output = subprocess.check_output(["curl", '%s%s' % (self.live_server_url, '/static/testapp/style.css')]) self.assertIn('background: blue', output) def test_requests_static_file(self): response = requests.get('%s%s' % (self.live_server_url, '/static/testapp/style.css')) response.raise_for_status() -
Import "blocktunes" could not be resolved Pylance report Missing Imports
urls.py of website from django.contrib import admin from django.urls import path, include from blocktunes import views #error (blocktunes is an app) urlpatterns = [ path('', include('blocktunes.urls')), path('admin/', admin.site.urls), ] Why is it showing cannot import? Settings.py (I have installed it as well) INSTALLED_APPS = [ 'blocktunes.apps.BlocktunesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Django Rest Framework - Nested response
Suppose there is question-answer web applicaton, Answer related to Question, and Reply related to Answer Now frontend has to display the question , answer and replies as. Question 1 Answer1 reply1 Question 2 Answer1 reply1 reply2 Answer2 Now, I want to know the efficient way to frame response of this Rest API, which fetches data of question , answer and replies. Anyone knows the efficient approach? -
Reverse for 'task' not found. 'task' is not a valid view function or pattern name
in task_list.html {{task.title}} works fine but 'task' in href few lines below doesn't work. It shows the error "NoReverseMatch at / Reverse for 'task' not found. 'task' is not a valid view function or pattern name." for the a tag in 2nd table row in task_list.html task_list.html: <h1>My To Do List</h1> <table> <tr> <th>Item</th> <th></th> </tr> {% for task in tasks %} <tr> <td>{{task.title}}</td> <td><a href="{% url 'task' task.title %}">View</a></td> </tr> {% empty %} <h3> No items in list</h3 > {% endfor %} </table> urls.py: from django.urls import path from .views import TaskList, TaskDetail urlpatterns = [ path('', TaskList.as_view(), name='tasks'), path('task/<int:pk>', TaskDetail.as_view(), name='tasks'), ] views.py: from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Task class TaskList(ListView): model = Task context_object_name = 'tasks' class TaskDetail(DetailView): model = Task context_object_name = 'task' template_name = 'base/task.html' -
Returning zip from DJango view using zip_file: could not find a easy way
I want to loop over all files of a folder to make a zip folder and before make zip, I need to filter row in files I have found a way to do it, but seems "hack" so I wonder if there is a good solution for tests, I have 2 files in my folder: file1.csv and file2.csv original file1.csv field1,field2,filed3 CI-S1-001,1,test1 CI-S1-002,1,test2 original file2.csv field1,field2,filed3 ZA-S1-001,1,test3 ZA-S2-002,1,test4 filtered_export view function will loop over the 2 files and filter rows based on first field as user have rigth on 'S1' and 'S3', the 2 rows of file1.csv and only the first row file2.csv will be return and write if zip files and the zip folder will contain 2 files ZIP file1.csv field1,field2,filed3 CI-S1-001,1,test1 CI-S1-002,1,test2 ZIP file2.csv field1,field2,filed3 ZA-S1-001,1,test3 def filtered_export(request): # site list available for user sites = ['S1','S3'] ... # retrieve the list of all files in study directory excluding 'archives' directory listOfFiles = getListOfFiles(path) # Create zip buffer = io.BytesIO() zip_file = zipfile.ZipFile(buffer, 'w') for file in listOfFiles: records = [] # read the files with open(path + file, newline='', encoding="utf8") as csvfile: has_header = csv.Sniffer().has_header(csvfile.read()) csvfile.seek(0) spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') csv_headings = ','.join(next(spamreader)) for row in … -
Django REST API Update list of data
I have an API for adding new members into the list and remove members from that list. By means If there are 2 members in a list then If I add another one member I wanted to append the latest member into the list. But that's not what happening for me. When I add new member into the list, previous 2 members data was removed. How can I solve this issue. As I'm just working backend, my work is to create an API for this function. The frontend developers will take care of the rest of the things. models.py class Batch(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length=350, null=True, blank=True) course = models.ForeignKey(TrnCourse, on_delete=models.CASCADE, related_name='batches') tutor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='handling_batches') members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='batches') serializers.py class MemberSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name') class BatchMemberSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True, allow_null=True) class Meta: model = Batch fields = ('members',) views.py class UpdateRemoveBatchMembersView(generics.RetrieveUpdateAPIView): def get_serializer_class(self): if self.request.method == 'GET': return BatchMemberSerializer return EditBatchMemberSerializer def get_queryset(self): course_id = self.kwargs['course_id'] batch_id = self.kwargs['pk'] return Batch.objects.filter(id=batch_id, course__id=course_id, course__institute=self.request.user.institute) From the frontend, the API response for PUT method will look like this { "members":[ ... ] } I just wanted … -
How to filter a model Django and compare against an id
I'm trying to filter a model called "CartItem" , that has a field called item , I want to check whether a product id is in this field. each cartitem instance is connected to a cart.id. The product id is taken from a form in templates. I currently have " {% if cartitem.objects.filter(item_id=product_id).exists %} " in the template, I also tried making an items list in the views.py , to try to use the "if in" statement in the template, based off the "items" contents. at the moment I get an error: TemplateSyntaxError Exception Value: Could not parse the remainder: '(item.id=product.id).exists' from 'cartitem.objects.filter(item.id=product.id).exists' Thanks models.py class CartItem(models.Model): item = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True) items_cart = models.ForeignKey('Cart', blank=True, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return 'item:{} cart:{} quantity:{}'.format(self.item, self.items_cart, self.quantity) views.py def cart_update(request): product_id = request.POST.get('product_id') cart_obj, new_obj = Cart.objects.new_or_get(request) cart_items = CartItem.objects.filter(items_cart_id=cart_obj) items = [] for item in cart_items: items.append(item.item.id) print(items) if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) cart_items = CartItem.objects.filter(items_cart_id=cart_obj) if product_obj in cart_items: cart_items.delete(product_obj) added = False else: newitem = CartItem(item=product_obj, items_cart=cart_obj, quantity=1) … -
Required field of html is not working with django template syntax
Required field html validation not working with django its not asking to select from the list do anyone knows how to solve it only its working when I remove the django template syntax <select name="assignee" required id="assignee" class="form-control"> {% for user in b %} <option>{{user.firstname}} {{user.lastname}}</option> {% endfor %} </select> -
Django - updating m2m field value after save
The problem is, that after saving a model instance with new m2m_field value, I want to automatically add some more related objects to it. class MyModel(models.Model): m2m_field = models.ManyToManyField("app.RelatedModel") @receiver(models.signals.m2m_changed, sender=MyModel.m2m_field.through) def m2m_field_changed(sender, instance, **kwargs): instance.m2m_field.add(related_object_instance) That obviously results in an infinite loop, because after adding the instance to the m2m_field, the receiver is fired again and so on. Is there a proper way to do it? Thanks for any help. -
Make a choices list for forms.py after receiving data from views.py in django
So this is the scenario. I allow my user to first input their vehicle brand with one form and then use another form to list down the models available for that vehicle brand. The information on the vehicles and the brands is stored in my database. Refer to this image to get a better idea... And this is my views.py...(INCOMPLETE FOR NOW) def driver_dashboard_trip_brand (request, brand): if request.method == "POST": form = AddVehicleForm(request.POST) else: form = AddVehicleForm() brands = VehicleBrand.objects.all() context = { "form":form, "brands":brands, "chosen_brand":brand } return render (request, "app/driver_dashboard.html", context) And my forms.py... class AddVehicleForm(forms.ModelForm): model = forms.ChoiceField() vehicle_colour = forms.ChoiceField(choices=COLOURS) vehicle_number = forms.CharField(max_length=8, widget=forms.TextInput(attrs={'placeholder': 'eg: CAB-1234'})) class Meta: model = Vehicle fields = ['model', 'vehicle_colour', 'vehicle_number'] So in order to set a query in the forms.py, I would first need to send the data from views.py to forms.py and THEN I also need to do a query. So my question is how can I query for all the car models from the VehicleModel database and create choices attribute for the form, once the user chooses the car brand. Any help would be greatly appreciated and I would definitely upvote your answer and all comments if I am … -
Create multiple tables in a single database in django
I created an app in Django and made migrations and migrated to my database "emp". Then I created another project with an app and I created a table in the same database emp and made migrations. Migrations were made but when I migrated it showed "No changes detected" and the table was also not created. When I did the same process in a different database it worked. I wanted to know that how can I create multiple tables in a single database Please Help!! -
Django Custom Form
so I'm trying to create a comment form, but I cannot make the form appear in the way I want. Let me explain: I want this: Using this code: <div class="ui action input"> <input type="text" placeholder="Search..."> <button class="ui icon button"> <i class="search icon"></i> </button> </div> And the form that I have to show the form I created in forms.py is: <form action="" method="POST"> <!-- NOVO COMMENT --> {% csrf_token %} <input type="hidden" name="post_id" value={{post.id}}> {{ c_form }} <button type="submit" name="submit_c_form" class="ui primary button mt-10 w-full"><i class="paper plane outline icon"></i>Send</button> </form> Which comes out like this: Here is my forms.py where I create the comment form: Thank you anyone out there that can help me :) -
How can I filter a Django_Table that display records from a Dict instead of a model
I would like to know if there is a way to filter on field in a Django table that is created with a dictionary instead of with a Model. I have a Model that has 2 properties: #models.py class DeviceConfiguration(Model): device = models.OneToOneField(Device, on_delete=models.CASCADE) config = models.JSONField() In that JSON lives some structured data that needs to be proccessed before i can present it in a table (It contains a dict with lists with dicts that needs to converted to a list of dicts). I have the following table that uses an Accessor to traverse my custom JSON: #tables.py class RawConfigTable(tables.Table): hostname = tables.Column(accessor=A('system__hostname')) version = tables.Column(accessor=A('system__version')) interface = tables.Column(accessor=A('interfaces__name')) status = tables.Column(accessor=A('interfaces__protocol')) speed = tables.Column(accessor=A('interfaces__speed')) class Meta: attrs = {'class': 'table table-condensed table-vertical-center', 'id': 'dashboard_table'} fields = ('hostname', 'version', 'interface', 'status', 'speed') sequence = fields order_by = ('hostname', ) In the views.py the table gets instanciated with the proccessed JSON as per documentation: #views.py class RawInterfaceList(View): """Displays all the interfaces from all devices in table form""" def get(self, request): all_configs = [] for device in Device.objects.all(): config = device.deviceconfiguration.config input = { 'system': config['system'], 'interfaces': config['interfaces'] } all_configs.append(proccess(input)) # This is the custom proccessing i was talking about table … -
I am not able to upload images for my E commerce application. I am getting following errors. Can anyone review my error?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/img/uploads/products_img/jet-black-half-sleeve-t-shirt-men-s-plain-t-shirts-106-1560838106.jpg Using the URLconf defined in Eshop.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P.*)$ The current path, img/uploads/products_img/jet-black-half-sleeve-t-shirt-men-s-plain-t-shirts-106-1560838106.jpg, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.