Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Download folder From Media
Django Download folder From Media In django Which method is user for Download complete directory to Client Machine from /media/ -
How do I fix the circular import in django
I am trying to simply put a 'Hello World' text on the server. And it brings an error. Project Urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] App Urls.py from django.urls import path from . import views urlpattern = [ path('', views.index,name = 'index') ] Views.py from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('<h1>Hello World</h1>') The Error it tells me: The included URLconf in myapp/urls.py does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
post() missing 3 required positional arguments: 'user', 'user_obj', and 'code'
class CodeAPIView(APIView): def post(self,request,user,user_obj,code): code2 = request.data['code'] if code2 == code: AuthAPIView.login(self,request,user,user_obj) else: return Response("the code is wrong!") this is my view, and I get an error. How can I fix it? -
For loop in django retrieving all users instead of one and M2M field data output
I have 2 Issues in Django: Below are my codes, whenever I am using For loop in my Template, it is retrieving not one user data, but all users/profile data. but when I use request.user.profile.first_name only then it works, but I am in a situation where i need to retreive data from many-to-many field and I have to use For loop, which brings me to my 2nd question I need to use For loop in many-to-many field to retreive the data, but it is fetching for all users, please can you correct me where I am doing wrong? or is there any alternate method to retreieve data without using for loop (one user/profile only post logging-in) models.py class Department(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) departments = models.ManyToManyField(Department) views.py def profilepage(request): profiles = Profile.objects.all() departments = Department.objects.all() context = { 'profiles': profiles, 'departments': departments } return render(request, 'profile.html', context) profile.html {% for profile in profiles %} First Name: {{profile.first_name}} {% for department in departments %} Department: {{department.name}} {% endfor %} {% endfor %} -
Zappa Django one lambda per app in a monorepo
My Django REST API is composed of multiples apps, one app per resource like that: ├── core │ ├── settings.py │ ├── urls.py ├── customers │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py ├── orders │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py The settings of the app are all in core/settings.py. How can I tell zappa to deploy each app in a different lambda function and configure API Gateway to handle the routing for each app? -
while using django_filters how to remove or edit filters field from URL
while using django_filters the url generated like this: http://127.0.0.1:8000/reports/?EmployeeId=SW1&start_date=07%2F28%2F2021&end_date=07%2F31%2F2021 I dont want to display this things "?EmployeeId=SW1&start_date=07%2F28%2F2021&end_date=07%2F31%2F2021" only id number should display like http://127.0.0.1:8000/reports/1 -
No "Copy content from" wagtail-modeltranslation button
The "COPY CONTENT FROM [available translation languages]" button is not showing in the admin page editing interface. The package was installed properly, following official documentation. What can cause the issue and how to fix it? -
Azure SQL database connection error with django
For my Django web app I'm getting this error when running python manage.py makemigrations I have googles this problem can't able to find solution. Can someone help me to find solution to this problem, I'm a beginner programmer. File "D:\Azure\newDjango\.venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "D:\Azure\newDjango\.venv\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'core_profilefeeditem'. (208) (SQLExecDirectW)") my settings.py file for database connection DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '<db-name>', 'USER': '<db-username>', 'PASSWORD': '<db-passord>', 'HOST': '<servername>.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'MARS_Connection': 'True', } } } my models.py where Profile page with user updates their images using rest_framwork as endpoint to show the user details and images from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings import uuid # Create your models here. def image_name_change(instance, filename): ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return filename # Changing the default authentication # ? https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#auth-custom-user class UserProfileManager(BaseUserManager): """Manager of User Profile""" def create_user(self, email, name, password=None): """Create new user profile""" if not email: raise ValueError("User must have an email address") … -
Rabbitmq installation throws dependency error
I installed rabbitmq version==3.18.19 and erlang = 23.2 win64 version respectively. After installation i give the rabbitmq plugins command : rabbitmq-plugins enable rabbitmq_management. It throws the below error. Any suggestions ? Enabling plugins on node rabbit@Rana-04: rabbitmq_management The following plugins have been configured: rabbitmq_management rabbitmq_management_agent rabbitmq_web_dispatch Applying plugin configuration to rabbit@COMPFIE2-04... Stack trace: ** (CaseClauseError) no case clause matching: {:error, {:missing_dependencies, [:eldap], [:rabbitmq_auth_backend_ldap]}} (rabbitmqctl 3.8.0-dev) lib/rabbitmq/cli/plugins/plugins_helpers.ex:107: RabbitMQ.CLI.Plugins.Helpers.update_enabled_plugins/4 (rabbitmqctl 3.8.0-dev) lib/rabbitmq/cli/plugins/commands/enable_command.ex:121: anonymous fn/6 in RabbitMQ.CLI.Plugins.Commands.EnableCommand.do_run/2 (elixir 1.10.4) lib/stream.ex:1325: anonymous fn/2 in Stream.iterate/2 (elixir 1.10.4) lib/stream.ex:1538: Stream.do_unfold/4 (elixir 1.10.4) lib/stream.ex:1609: Enumerable.Stream.do_each/4 (elixir 1.10.4) lib/stream.ex:956: Stream.do_enum_transform/7 (elixir 1.10.4) lib/stream.ex:1609: Enumerable.Stream.do_each/4 (elixir 1.10.4) lib/enum.ex:2161: Enum.reduce_while/3 {:case_clause, {:error, {:missing_dependencies, [:eldap], [:rabbitmq_auth_backend_ldap]}}} -
What is the best language when it comes to web developing?
So this has come across my mind alot, and I just want to know what the community thinks, because I am sure alot of people have had this same question as me. What do you guys think is the best web developing language when it comes to Security, simplicity, and effectiveness? I have heard React/Django is really good, but I am not really sure. Thanks in advance! :) -
How to add profile_pic field from another model in one model
I want to add profile_pic in Blog View page which is in my Profile model models.py class Profile(models.Model): user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") class StudentBlogModel(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True,null=True) snippet = models.TextField(max_length=255) Views.py class BlogView(ListView): model = StudentBlogModel template_name = 'blog/home.html' context_object_name = "StudentBlogModel_list" paginate_by = 10 home.html <div class="container"> <div class="row"> <div class="col-lg-8"> <hr> <div class="profile-feed"> <div class="d-flex align-items-start profile-feed-item"> <img src="{{ }}" alt="profile" class="img-sm rounded-circle mb-5 mx-2"> <div class="ml-4"> <h6> {% if StudentBlogModel.author.first_name or StudentBlogModel.author.last_name%} <small class="card-title">{{StudentBlogModel.author.first_name|capfirst}} {{StudentBlogModel.author.last_name|capfirst}} </small> {% else %} <small class="card-title">{{StudentBlogModel.author.username|capfirst}}</small> {% endif %} <small class="ml-4 text-muted"><i class="mdi mdi-clock mr-1"></i> {{StudentBlogModel.post_date}}</small> </h6> <p> {{StudentBlogModel.title}} </p> what to write in src to get profile pic of particular author -
'NoneType' object has no attribute 'user' DRF
I have got two class based views. class AuthAPIView(APIView): def post_code(self, request, format=None): data = request.data username = data.get('username', None) password = username user = authenticate(username=username, password=password) if user is not None: if user.is_active: code = random_code_generator() user_obj = User.objects.get(username=username) Code.objects.create(phone_number=user_obj,code=code) now = datetime.now() current_time = now.strftime("%H:%M:%S") hour = current_time.split(":")[0] minute = current_time.split(":")[1] send(str(username),code,int(hour),int(minute)+2) return code def post(self,request,format=None): self.post_code(request) return Response("we have sent a code") class CodeAPIView(APIView): def post_code(self,request): data = request.data code2 = data.get('code', None) code = AuthAPIView.post_code(self,request) user = AuthAPIView.post_code(self,request).user if code2 == code: login(request, user) token = Token.objects.get(user=user) return Response(token.key) Code.objects.filter(phone_number=user_obj,code = code).delete() else: return Response("the code is wrong!") def post(self,request): self.post_code(request) here is my two views. I try to access user variable which it is stored in AuthAPIView.post_code in second class . user = AuthAPIView.post_code(self,request).user. where is my mistake? -
cannot import name 'S3' from 'froala_editor'
I am trying to generate a hash value for the folder on Amazon S3 with a package called "Froal_editor" in Django. I am following this tutorial. After everything is setup I installed Froala_Editor with command pip install django-froala-editor which successfully installed the package. I am facing the error cannot import name 'S3' from 'froala_editor when I am trying to import from froala_editor import S3 Any help in this regard would be highly appreciated. -
yaml field formatting display in Django admin pane
I want to display the field in yaml formatting in Django admin. Is there a way to achieve this? I tried exploring but didn't find much about yaml field in Django -
Django: To add a Link to custom page from Django admin form of a model
I want to add a link in admin/seo/seolist/1/change/ form which redirect to a custom html select_page.html and selects an input. -
Filter Dropdown based on Logged in User
I have models as below models.py user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.EmailField() role_id = models.ForeignKey("Role",on_delete=models.SET_NULL,null=True,related_name="role_id", default=1) lead_id = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="parent_id" ,default=1) department_id = models.ForeignKey("Department" ,on_delete=models.SET_NULL,null=True,default=1) team_id = models.ForeignKey("Team" ,on_delete=models.SET_NULL,null=True,default=1) class Timesheet (models.Model): date = models.DateField(auto_now=True) Task = models.TextField(null=True) employee = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True ) supervisor = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="supreviosr") my filters.py class TimesheetFilter(django_filters.FilterSet): class Meta: model = Timesheet fields= ['employee'] when a lead logged in , i want lead's employee's to be shown on django's filter dropdown box (this where i am stuck) 2.based on selected employees filter a table(was able to achieve this) looked at this How do I filter values in a Django form using ModelForm? wondering if i can apply same approach for my requirement, any suggestions would be much appreciated Thank you. -
Is the server running on host "localhost" (127.0.0.1)
I am deploying a django app for the first time to Heroku. I used the following: heroku run python manage.py migrate and it returns : Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? In my settings.py i have : DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } and at the bottom : try: from .local_settings import * except ImportError: pass in the local_settings.py I have : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newapp_development', 'USER': 'postgres', 'PASSWORD': '#####', 'HOST': 'localhost', 'PORT': '5432', } } Do you know why is the error message please ? Also, note that local_settings is added to . gitignore. Thank you for your help. -
How to solve the error while building a VueJS project?
I am using VueJS for front-end and Django on back-end. For production I moved all my VueJS compiled bundel to Static/dist in django. And I blocked the content of index.html in VueJS to base.html in django. And changed the url.py such that when localhost:8000 is called it gives base.html which gives index.html of VueJS. When I am trying to build using npm run buid it is throwing errors as shown ERROR Build failed with errors. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! e_cell_frontend@0.1.0 build: `vue-cli-service build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the e_cell_frontend@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/vagrant/.npm/_logs/2021-08-05T04_54_44_578Z-debug.log The log file is as shown: 0 info it worked if it ends with ok 1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'build' ] 2 info using npm@6.14.4 3 info using node@v10.19.0 4 verbose run-script [ 'prebuild', 'build', 'postbuild' ] 5 info lifecycle e_cell_frontend@0.1.0~prebuild: e_cell_frontend@0.1.0 6 info lifecycle e_cell_frontend@0.1.0~build: e_cell_frontend@0.1.0 7 verbose lifecycle e_cell_frontend@0.1.0~build: unsafe-perm in lifecycle true 8 verbose lifecycle e_cell_frontend@0.1.0~build: PATH: /usr/share/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/vagrant/VueJS/e_cell_frontend/node_modules/.bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/home/vagrant/.local/bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin … -
Django.db.models.deletion related_objects takes 3 positional arguments
I'm upgrading my project from Django 2.2 to 3.2 and wracking my brain at what seems to be a bug in their code. I have a test that does a simple DELETE request to a resource (incidentally a DjangoRestFramework resource), and a crash happens inside django.db.models.deletion. here is the relevant part of the stack trace: self = <django.db.models.deletion.Collector object at 0x7f7870265ac8> objs = [<Category: Test category 0>], source = None, nullable = False collect_related = True, source_attr = None, reverse_dependency = False keep_parents = False, fail_on_restricted = True def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False, keep_parents=False, fail_on_restricted=True): """ Add 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler. If the call is the result of a cascade, 'source' should be the model that caused it and 'nullable' should be set to True, if the relation can be null. If 'reverse_dependency' is True, 'source' will be deleted before the current model, rather than after. (Needed for cascading to parent models, the one case in which the cascade … -
Can foreign key take up value other then choice?
I am having trouble with the foreign key I created. I need some advice/help from the pros out here. I have an app using django. And inside there is a tab called 'Add Device'. This tab's job is generate a form to add new device using 2 models in the same form into the SQL DB which is created. The following are the codes I have coded: models.py class Device(models.Model): hostname = models.CharField(max_length=50) ipaddr = models.CharField(max_length=15) date_added = models.DateTimeField(default=timezone.now) def __str__(self) return self.hostname class DeviceDetail(models.Model): hostname = models.ForeignKey(Device, on_delete=models.CASCADE) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.CharField(max_length=30) subnetmask = models.CharField(max_length=30) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) device_model = models.CharField(max_length=50) def __str__(self): return self.hostname views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) if device_frm.is_valid(): device_frm.save() deviceid = Device.objects.aggregate(Max('id'))['id__max'] device = Device.objects.all() ##Part A1 if dd_form.is_valid(): deviceD = dd_form.save(commit=False) deviceD.device = Device.objects.get(id=deviceid) deviceD.save() else: print(dd_form.errors) return render(request, 'interface/device_added.html',{'devices':device}) forms.py class DeviceForm(ModelForm): class Meta: model= Device fields= ['hostname', 'ipaddr'] class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= ['hostname', 'ssh_id','ssh_pwd', 'mgt_interface', 'mgt_ip_addr', 'subnetmask','enable_secret','device_model'] The above codes is workable if my foreign key is device_model. But the problem is this foreign key, it links up the table together … -
Understanding post_save and m2m_changed signals in Django(2.2)
I have a notifications model in Django with a ManyToMany field related to Users. The idea I had was that I would assign all users to a notification on its' creation, then individual users who cleared that notification on the frontend would be removed from the M2M relationship on the backend. Once the notification had no more users within its' M2M field, the instance would delete itself. Initially, I tried assigning all users to a notification within its' post_save signal: @receiver(post_save, sender=Notification) def contract_post_save(sender, instance, created, **kwargs): from core.api.serializers import NotificationSerializer if created: users = User.objects.all() instance.users.add(*users) return Ofcourse the M2M relations I added didn't save which I found from StackOverflow was because "M2Ms are saved after instances are saved and thus there won't be any record at all of the m2m updates" and I would have to use the m2m_changed signal instead. So I added this signal to see what data would come through (I didn't make any changes to the post save signal above): @receiver(m2m_changed, sender=Notification.users.through) def test(sender, instance, action, reverse, model, pk_set, **kwargs): print(sender) print(instance) print(action) print(reverse) print(model) print(pk_set) The actions that trigger the m2m_changed signal are pre_remove and post_remove, and the pk_set contains all of my … -
How can I show only one author (who has logged in) instead of list of all the authors, while creating post?
I am new to django. I am creating a blog project where the user who has logged in can create post. The problem that i am facing is, i am getting a list of all logged-in authors while i want option of only author who has just logged in. see this pic of create post page- Please help me with this. Below are my Codes - #models.py from django.db import models from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.conf import settings from django.utils import timezone from ckeditor.fields import RichTextField # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE,blank=False,null=True) title = models.CharField(max_length=200) header_image = models.ImageField(blank = True, null=True, upload_to="images/") text = RichTextField(blank=True, null=True) created_date = models.DateTimeField(blank = True, null= True) published_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='blog_posts') def get_absolute_url(self): return reverse("blog:post_detail", kwargs={'pk':self.pk}) def total_likes(self): return self.likes.count() def approve_comments(self): return self.comments.filter(approved_comment=True) # from total comments on post , only approved comments will be filtered and returned (shown on blog ), unapproved comments will be rejected. def publish(self): self.published_date = timezone.now() # self - connects method and its arguments to instance of a class. self.save() def __str__(self): return self.title … -
I cannot set a value to django-select2 ModelSelect2Widget using val() function
In my django app I have a CenterModel and a ProvinceModel, each center has a province_id field. I have define a form for Center using ModelSelect2Widget (django_select2) for province_id. I want to set the selected value to the province_id field in the template using javascript but the following code is not working: $("#id_province_id").val(response.province_id) $('#id_province_id').trigger('change'); but these lines are not working, they are NOT setting the value to the province_id field. Instead if the field has some previosly selected value the '.val()' funtion clears that value. I double checked and the response.province_id is storing a valid province id. Why I cannot set a value to the selct field? I am working with django-select2==7.7.1 class CenterModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, unique=True,blank=False, null=False) province_id = models.ForeignKey("ProvinceModel", verbose_name=_("Provincia"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") municipality_id = models.ForeignKey("MunicipalityModel", verbose_name=_("Municipio"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") from django_select2.forms import ModelSelect2Widget class CenterForm(forms.ModelForm): class Meta: model = CenterModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(), search_fields=['des_prov__icontains'], attrs={'style': 'width: 100%;'}), 'municipality_id' : ModelSelect2Widget(model=MunicipalityModel, queryset=MunicipalityModel.objects.filter(), search_fields=['municipio__icontains'], dependent_fields={'province_id': 'cod_prov'}, attrs={'style': 'width: 100%;'}), } -
Integration between google maps and django
I 'm working on a django app based on location where I 've a model shop like this : class Shop(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=100) city = models.CharField(max_length=50) location = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) suppose that in my views i 've a function that filter the db based on a location (long , lat) and rener nearby shops , i will use google maps api here to render a map and show center based on the sent (long , lat) and markers for the nearby shops , now i want to enable the user to change the location on the map by drag and set a new center and listen to this in my view to run filter again and apply changes ? any help for this , thanks . -
message:New application object missing required attributes
the error I got in the wfastcgi-enable query is as follows C:\Users\Administrator>wfastcgi-enable ERROR ( message:New application object missing required attributes. Cannot add duplicate collection entry of type 'application' with combined key attributes 'fullPath, arguments' respectively set to 'c:\python39\python.exe, c:\python39\lib\site-packages\wfastcgi.py' . ) An error occurred running the command: ['C:\Windows\system32\inetsrv\appcmd.exe', 'set', 'config', '/section:system.webServer/fastCGI', "/+[fullPath='c:\python39\python.exe', arguments='c:\python39\lib\site-packages\wfastcgi.py', signalBeforeTerminateSeconds='30']"]