Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up Django Machina custom permissions
I am new to Django and python. I have been able to alter a custom user model so that the user signup form presents the user with categories and category subforums populated from Machina tables. An example would be a user choosing the category of "Biology" (category forum) and a subcategory of microbiology (subforum of the category "Biology"). When the users view the main forum page, I only them to see a couple of site wide forums and the category/subforum they chose upon registration. I am not sure how to customize Machina to accomplish this. I found the forum permissions handler.py here: https://github.com/ellmetha/django-machina/blob/a92041c2854bee6b80d418fabd4cec5caac91dc3/machina/apps/forum_permission/handler.py#L300 It seems to offer some possible ways to accomplish what I want to do, but I am not sure of a good approach. Any suggestions for customizing which forums users have access to? -
argument of NoneType is not iterable dictoinary
Below is the dictionary I am trying to access { "skipped":"", "skip_traced":"Both", "opt_out":"Both", "filters_condition":"and" } if 'Both' not in data['skip_traced']: pass The above code show me error argument of NoneType is not iterable when I reach this command. -
Django Taggit - Autocomplete Light (Guidance with configuring)
I have Taggit fully up and running and would like to configure Autocomplete Light in order to enable the Select2 dropdown when users select their preferred tags within my application. I have installed DAL, dal_select2 along with dal_queryset_sequence libraries. I already have a form created where my users can simply upload a photo, add content and a TagField. Although, the TagField currently operates as a normal text field (But the tags do successfully save through to my Taggit app) - I'm just struggling to get the Select2 dropdown working. Here are my settings (as far as the Installed Apps are concerned: Settings.py INSTALLED_APPS = [ 'core.apps.AConfig', 'users.apps.UConfig', 'crispy_forms', 'emoji_picker', 'taggit', 'dal', 'dal_select2', 'dal_queryset_sequence', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] Within my Views.py from dal import autocomplete class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tag.objects.none() qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs URLs.py from core.views import TagAutocomplete urlpatterns = [ url( r'^tag-autocomplete/$', TagAutocomplete.as_view(), name='tag-autocomplete', ), ] Forms.py import dal from dal import autocomplete from taggit.models import Tag class PostForm(autocomplete.FutureModelForm): tags = forms.ModelChoiceField( queryset=Tag.objects.all() ) class Meta: model = Post fields = ('__all__') … -
Is there any way to change the email scope to username scope in django
I just would like to know how to copy the email scope to the username scope in Django and for Google OAuth 2.0. -
Chained dropdown validation error. Form works
Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error. It is a basic 3 field form creating a person object with name, country and city. Views.py def person_create_view(request): form = PersonCreationForm() if request.method =='POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'store/ho.html', {'form': form}) Forms.py class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id = country_id) except(ValueError, TypeError): pass elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') In forms.py line 7 where it says- self.fields['city'].queryset = City.objects.none() this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away. error: "Select a valid choice. That choice is not one of the available choices" In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine. It is almost like having a pause at that line and the system suddenly realizes that there is more code. How do I fix … -
Is it safe to call emit_post_migrate_signal from within a Django migration?
Background My original issue that lead me to this was my desire to create a Group within a django migration (not a problem) and then also assign permissions to that Group within a migration (problem arises here). It seems that in Django that ContentTypes and Permissions are created post-migration. So migrations cannot assign Permissions to Groups because the Permissions don't exist yet. ContentType and Permission generation is triggered by the post_migrate signal, which appears to be sent automatically after all migrations have been applied. There is this work around, in which you manually call emit_post_migrate_signal from within your migration. This will generate all ContentTypes and Permissions, and then the migration can indeed successfully apply them to the Group. Question My question is: is this actually safe to do? I can't find any documentation on the emit_post_migrate_signal function, and emitting a post_migrate signal in the middle of a migration seems like a recipe for something to go wrong (either now or in the future). -
Migration from Django 2 to 3 and url with localization
I am using Django 3.2.3, Apache and Daphne. Daphne is very slow. I use Apache like a proxy to send the request to Daphne : <VirtualHost *:443> AllowEncodedSlashes On ServerName mysite.com ServerAdmin admin@gmail.com ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET" env=CORS Header set Access-Control-Allow-Credentials "false" env=CORS SSLCertificateFile /etc/letsencrypt/live/****/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/***/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> I launch Daphne with the command : daphne -p 8001 asgi:application When I access to my website, the log of Daphne are : 2021-06-04 21:17:17,821 INFO Adding job tentatively -- it will be properly scheduled when the scheduler starts 2021-06-04 21:17:17,865 INFO Added job "my_job" to job store "default" 2021-06-04 21:17:17,866 INFO Scheduler started 2021-06-04 21:17:17,909 INFO Starting server at tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,912 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2021-06-04 21:17:17,913 INFO Configuring endpoint tcp:port=8001:interface=127.0.0.1 2021-06-04 21:17:17,919 INFO Listening on TCP address 127.0.0.1:8001 2021-06-04 21:17:20,053 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" (scheduled at 2021-06-04 21:17:20+02:00) 2021-06-04 21:17:20,054 INFO Job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:20 CEST)" executed successfully 2021-06-04 21:17:40,105 INFO Running job "my_job (trigger: cron[second='*/20'], next run at: 2021-06-04 21:17:40 CEST)" (scheduled at 2021-06-04 21:17:40+02:00) … -
Models Mixin ManytoMany
I want to implement in django a model mixin. I have in mixin.py: class RightsModelRelation(models.Model): user_link = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, default=None, related_name="%(class)s_rights_user") right_to_view = models.BooleanField(default=True) right_to_change = models.BooleanField(default=False) right_to_delete = models.BooleanField(default=False) class RightsModelMixin(models.Model): rights_link = models.ManyToManyField(RightsModelRelation, default=None, related_name="%(class)s_rights_link") models.py: class Address( RightsModelMixin,models.Model): lastname = models.CharField(max_length=255, default="", ) firstname = models.CharField(max_length=255, default="", blank=True, null=True) But this don't work. Can anyone help me to implement a manytomany models mixin? -
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 …