Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Defining choices outside of model producess fields.E005 error [duplicate]
I have the following code in my models.py: from django.db import models from django.utils.translation import gettext_lazy as _ class Sport(models.IntegerChoices): SWIMMING = 0, _("Swimming") HIKING = 1, _("Hiking") RUNNING = 2, _("Running") class Manufacturer(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) name = models.CharField( max_length=255, help_text="Manufacturer name as displayed on their website", ) url = models.URLField(blank=True) sport = models.PositiveSmallIntegerField(choices=Sport) class OrganisationClass(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) class_name = models.CharField(max_length=64, blank=False) description = models.CharField( max_length=255, blank=False, ) sport = models.PositiveSmallIntegerField(choices=Sport) which produces the FAIClass.sport: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. when I run manage.py check and I don't understand why. I got the idea to do it based on this answer, I'd really appreciate if someone could help. -
django: contol access to pages by many to many relation
I have a problem for block access to not authorized user in specific pages. List of that users is stored in Many to Many model in Project object. Below is models.py class Project(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="projects_as_owner", null=True) project_managers = models.ManyToManyField(User, related_name="projects_as_pm", blank=True) name = models.CharField(max_length=200) description = models.TextField(blank=True) date_of_insert = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Milestone(models.Model): project_fk = models.ForeignKey(Project, related_name="milestones", on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField(blank=True) date_of_insert = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name And views.py with class I have problem class NewMilestone(LoginRequiredMixin, generic.CreateView): model = Milestone fields = ['name', 'description'] lookup_url_kwarg = 'p_id' template_name = 'main/new_milestone.html' # ... two functions, that work good, not important here ... def get_queryset(self): qs = super(NewMilestone, self).get_queryset() project = Project.objects.get(id=self.kwargs['p_id']) if(qs.filter(project_fk__owner=self.request.user).exists() or User.objects.filter(id=self.request.user.id).filter(projects_as_pm__id=project.id).exists()): return qs else: return Http404("You are not authenticated to this action") Objective here is here to allow authenticated users (owner and project manager/s) to enter this view and for anybody else show info about declined access. Problem is that, that worked well on checking ONLY ownership. When I added that part about project manager(after 'or') program allows any user to access this view with link. I tried many configuration for that second 'if' statement every single one … -
Django, Docker, Nginx, cant find static file
I just cant wrap my head around how to properly write a nginx.conf file. My nginx container in docker keeps giving me error 2022/10/03 12:33:28 [error] 31#31: *1 open() "/usr/src/app/staticblog/style.css" failed (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /static/blog/style.css HTTP/1.1", host: "localhost:1337", referrer: "http://localhost:1337/profile/login" nginx.conf file upstream blog { server back:8000; } server { listen 80; location /{ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://blog; } location /static/ { alias /usr/src/app/static; } location /media/ { alias /usr/src/app/media; } } I feel like im just writing conf file wrong, but I cant wrap my head around directories in docker and how to properly manage them UPDATE: as @HemalPatel mentioned, I messed some slashes. Now I think I might as well got confused with setting.py file xD STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "blog/static/", ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Im so sorry its such a dumb question -
Customize the display to reset password
I would like to customize the view on the password reset process on django, not using the default view, myproject/urls.py from django.contrib.auth import views as auth_view urlpatterns = [ ....... path('', include('django.contrib.auth.urls')), path('reset-password/',auth_view.PasswordResetView.as_view(template_name='account/ password_reset.html'),name=' reset_password'), path('password_reset/done/',auth_view.PasswordResetDoneView.as_view(template_name='account/ password_reset_done.html'),name='password_reset_done'), path('reset/<uidb64>/<token>',auth_view.PasswordResetConfirmView.as_view( template_name='account/password_reset_form.html'),name='passwor_reset_confirm'), path('reset/done/',auth_view.PasswordResetCompleteView.as_view(template_name='account/ password_reset_complete.html'),name='password_reset_complete'), ] password_reset.html {% extends 'layout/base.html' %} {% block content %} <div class="row"> <div class="col s4 offset-s4"> <h5>To reset your password please enter your email</h5> <form method="POST"> {% csrf_token %} {{form}} <button class="btn waves-effect waves-light" type="submit">send </button> </form> </div> </div> {% endblock content %} password_reset_done.html {% extends 'layout/base.html' %} {% block content %} <h2>password reset</h2> <p>We have emailed you a reset link,If you do not receive a message, check your Spam</p> {% endblock content %} password_reset_form.html {% extends 'layout/base.html' %} {% block content %} <div class="row"> <div class="col s4 offset-s4"> <h5>Please enter your new password</h5> <form method="POST"> {% csrf_token %} {{form}} <button class="btn waves-effect waves-light" type="submit">Change </button> </form> </div> </div> {% endblock content %} password_reset_complete.html {% extends 'layout/base.html' %} {% block content %} <p>Your password has been changed. You can go ahead and log in now. <br> <a href="{% url 'account:login' %}">Login</a></p> {% endblock content %} Despite this I still have the default display -
Could not parse the remainder: '()' from 'forloop.counter|add:page_obj.start_index()'
I am trying to use a value 'start_index' from paginator's 'get_page()' object. This is required so my for loop can display id of an element according to the amount of previus elements in earlier pages. When i try to add this value to the forloop counter inside a template i get next error: my view: def openAllOrders(request): orders = cache_getFilteredOrders(request) orders_per_page = 10 paginator = Paginator(orders, orders_per_page) page_number = int(request.GET.get('page', 1)) page_obj = paginator.get_page(page_number) orders_before = (page_number-1) * orders_per_page page_orders = page_obj.object_list tbody_html = getOrdersTable(request, page_orders, orders_before) context = dict(tbody=tbody_html, page_obj=page_obj, type=request.GET.get('type'), date_start=request.GET.get('date_start'), date_end=request.GET.get('date_end'), orders_amount=len(orders),) return render(request, "order.html", context) page_obj.start_index() value in debugger: what am i doing wrong, and how should i add this value to forloop counter correctly? Thanks in advance! -
Share Custom User model between two Django projects (same db)
i have two Django project, sharing the same DB (postgres) The first one is an onboarding project for the users where i store the user data. The second one is the project where all the entities related to the user are. For example project one has only Users, project two has Cars and those two models are going to be related. I want to get the users from the first project and "use" them in the second one. I read some articles on how to do this, it seems that i should recreate the User model on project 2 and fake the migrations but i don't really like this way. I'm new to Django can you please help me understanding the best practice to achieve this? -
change "Delete" label beside can_delete checkbox in inlineformset_factory in django
I have two django models: Customer and Agent. Agent has foreign key to Customer (each customer can have lots of agents). I have this CBV: class CustmerAgentsEditView (SingleObjectMixin, FormView): model = models.Agent template_name = 'customer_agents_edit.html' def get(self, request, *args, **kwargs): self.object = self.get_object(queryset=models.Customer.objects.all()) # object.fields[].label='حذف' return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object(queryset=models.Customer.objects.all()) return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return CustomerAgentsFormset(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): form.save() return HttpResponseRedirect(self.get_success_url()) everything works well. the output have "Delete" checkbox which lets to remove an agent related to customer. label beside this Delete checkbox is Delete. I just want to change it to "REMOVE!!!". also in my forms.py I have just this code: CustomerAgentsFormset = inlineformset_factory(Customer, Agent, fields=('name', 'email', 'phone', 'mobile', 'role', 'customer'),extra= 2, can_delete=True) how can I do??? thanks for your answers. this is what I mean: enter image description here -
How to use Anaconda packages with AWS EB Django app
I am trying to deploy a django application with AWS Elastic Beanstalk, however it is not clear to me, how to use the installed Anaconda packages. I have successfully installed my conda packages using the .config within .ebextensions, however I don't know how to serve them to my django app. I've tried adding them to a .pth file, but still got no module error. files: "/var/app/venv/*/lib/python3.7/site-packages/conda.pth": mode: "000644" owner: root group: root content: | /miniconda3/lib/python3.7/site-packages If you have any link where I can read about, would be appreciated. Thank you -
Django-taggit: how to retrieve all tags filtered by a certain type of posts
I'm building a blog, and I have two status for a post, Published and a Draft. I wanto to display all tags of all published posts using Django-taggit. here's how a get all tags for all kind of posts, Published and Draft in my view: object_list = Post.published.all() tags = Tag.objects.filter() And I want to get only tags for published posts I got stuck, help! -
How can I prepopulate this field in my models? Django
I want that when I try to create a new account, the site_name field is prepopulated with the site that has it for instance, an account under reddit should have a site_name prepopulated with reddit.com already, instead of having to pick from the list of sites here is my class view for account creating an account: class AccountCreateView(LoginRequiredMixin, CreateView): model = Account template_name = "account_new.html" fields = ( "site_name", "username", "password", ) the rest of my views: class HomePageView(ListView): model = Site template_name = "home.html" def get_queryset(self): try: return Site.objects.filter(author=self.request.user) except: return HttpResponse("Login please!") class SiteDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Site template_name = "site_detail.html" def test_func(self): obj = self.get_object() return obj.author == self.request.user class SiteDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Site template_name = "site_delete.html" success_url = reverse_lazy("home") def test_func(self): obj = self.get_object() return obj.author == self.request.user class SiteEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Site template_name = "site_edit.html" fields = ("siteName",) def test_func(self): obj = self.get_object() return obj.author == self.request.user class AccountDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Account template_name = "account_delete.html" slug_field = "slug_field" slug_url_kwarg = "slug_field" success_url = reverse_lazy("home") class AccountEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Account template_name = "account_edit.html" fields = ( "username", "password", ) slug_field = "slug_field" slug_url_kwarg = "slug_field" class SiteCreateView(LoginRequiredMixin, … -
django get an unexpected keyword argument 'slug'
I get error but I can't understand how to fix it: (MainPage.get() got an unexpected keyword argument 'slug') This is my model: class Book(models.Model): title = models.CharField(max_length=256) price = models.IntegerField() category = models.ForeignKey('Category', on_delete=models.PROTECT) created_date = models.DateField(auto_now_add=True) description = models.TextField(blank=True, null=True) count = models.IntegerField(default=0) author = models.ForeignKey('Author', on_delete=models.PROTECT) class Category(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(blank=True, unique=True, allow_unicode=True) created_date = models.DateField(auto_now_add=True) This is my view: class MainPage(View): def get(self, request): books = models.Book.objects.all() return render(request, 'core/index.html', {'books': books}) class CategoryPage(View): def get(self, request): categories = models.Category.objects.all() return render(request, 'core/category.html', {'categories': categories}) This is my urls: urlpatterns = [ path('', views.MainPage.as_view(), name='MainPage'), path('category/', views.CategoryPage.as_view(), name='Category'), path('category/<slug:slug>/', views.MainPage.as_view(), name='BookList')] -
javascript query for 3 dependent cascading drop down for django
I want to design three dependent drop-down menus in Django using javascript. I can design for two variables. Can anyone help me with three variables? Here I am writing code for two variables. $(document).ready(function(){ var $d = $("#d"); var $E = $("#E"); var $options = $E.find('option'); $d.on('change',function(){ $.html($options.filter('[value="'+ this.value +'"]')); }).trigger('change'); }); -
wait for an asyn_task to complete or complete it in background
I have some functions in my Django application, that takes lot of time (scraping using proxies), it takes sometimes more than 30sec and is killed by gunicorn and AWS server due to timeout. and I don't want to increase the timeout value. A solution that came to my mind is to run these functions as a async_task using django-q module. Is it possible to do the following: when a view calls the long function, Run the function in async way if it returns a result in a pre-defined amount of time return the result to user. If not, return an incomplete result and continue the function in the background (The function changes a model in the database) no need to notify the user of changes. -
Using Values after Cast and Replace in Django ORM
Dummy data: field_1 price lot 1 1,333.00 lot 1 348.39 lot 2 98.00 The objective is to add the values of price Since price are strings representing numbers, Cast and Replace are used to remove the thousand comma separator and perform the sum. If I want to make the total sum, it works without any problem: total_price = ( myModel.objects.filter(status='Active', project_id=pid) .annotate( cleaned_total=Replace('price', Value(','), Value('')) ) .annotate(float_total=Cast('cleaned_total', FloatField())) .aggregate(Sum('float_total')) ) total_price output: {'float_total__sum': 1779.39} The problem is that I would like to group the sum, and for that I use .values('field_1') and I would like the result to be something like this: <QuerySet [{'field_1': 'lot 1', 'float_total__sum': 1681.39}, {'field_1': 'lot 2', 'float_total__sum': 98.0}] What I've tried: total_price_grouped = ( myModel.objects.filter(status='Active', project_id=pid) .values('field_1') .annotate( cleaned_total=Replace('price', Value(','), Value('')) ) .annotate(float_total=Cast('cleaned_total', FloatField())) .aggregate(Sum('float_total')) ) But unfortunately that gives me the following result: {'float_total__sum': 1779.39} If I don't use Cast and Replace, the sum is grouped correctly as desired but those values with thousand comma separator are not added correctly: total_price_grouped = myModel.objects.filter(status='Active', project_id=pid).values('field_1').annotate(sum=Sum('price')) How could I do the sum by combining values, replace and cast? -
Django add every user in foreign key model with default values
I have created a Django model with a foreign key from user, I want that all created user before be created in that table with a default value: Models.py from django.contrib.auth.models import User class UserProfiles(models.Model): myuser = models.OneToOneField(User, on_delete=models.CASCADE) userstatus = models.CharField(default='active', max_length=20) Can you help me that I can migrate this table and be created to all users who are registered before? -
Custom url doesn't work in Django for views
I have the following setup in proj.urls.py : urlpatterns = [ path('', admin.site.urls), path('api/v1/prealert/', include('prealert.urls')), ] Then in my app prealert, this is my setup for URLs (prealert.urls.py) , I have : app_name = 'prealert' urlpatterns = [ path('search_holding_certificate/', views.search_housing_certificate_view, name='search-hc') ] This is my view : @csrf_protect def search_housing_certificate_view(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = HousingCertificateSearchForm(request.POST) # check whether it's valid: if form.is_valid(): lot = ManagementByLot.objects.all() customer = form['customer'].value() product = form['product'].value() ware = form['ware'].value() season = form['season'].value() entity = form['entity'].value() url = f"{reverse('admin:prealert_managementbylot_changelist')}?customer={customer}&product={product}" return HttpResponseRedirect(url) # if a GET (or any other method) we'll create a blank form else: form = HousingCertificateSearchForm() return render( request, 'admin/search_housing_certificate.html', {'form': form} ) When I access the view via this URL it doesn't work: http://127.0.0.1:8000/api/v1/prealert/search_holding_certificate/ unless I add on the default Django URL the word admin that's when it works: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/prealert/', include('prealert.urls')), ] What causes this? Am using Django 4.0.3 -
Fill the db with fake data
def _create_sources(fake, source_number): obj_list = [ Source( name=fake.sentence(nb_words=10, variable_nb_words=True), url=fake.url(), isbn_10=fake.isbn10(), isbn_13=fake.isbn13(), ) for _ in range(source_number) ] counter = 0 for obj in obj_list: Source.objects.bulk_create([obj]) print("{} {}".format(Source._meta.object_name, str(counter))) counter +=1 I fill my database with fake data. It is necessary for both debugging and even for development. By the way, it has nothing to do with tests. Initially I did: Source.objects.bulk_create(ob_list) It worked. But it the computer kept silence for a long time. And I decided to print a notification. My code is clumsy: I bulk_create just one object,having converted it into a list. Could you help me find a more elegant solution? -
Submitting a form in Django
I'm following a tutorial on youtube to create a Netflix clone. When I clicked the create profile button, the form data was cleared, but it didn't redirect me to the ProfileList page. Does it mean that the form is not valid? Thanks for your help. views.py class ProfileCreate(View): def get(self,request,*args, **kwargs): form=ProfileForm() return render(request,'profileCreate.html',{ 'form':form }) def post(self,request,*args, **kwargs): form=ProfileForm(request.POST or None) if form.is_valid(): #print(form.cleaned_data) profile = Profile.objects.create(**form.cleaned_data) if profile: request.user.profiles.add(profile) return redirect('core:profile_list') return render(request,'profileCreate.html',{ 'form':form }) ProfileCreate.html {% extends 'base.html' %} {% load static %} {% block tittle %} Profile create {% endblock tittle %} {% block content %} {% include 'partials/navbar.html' %} <section class='bg-primary_black min-h-screen bg-cover py-20 md:py-32 flex-col flex items-center' style="background-image:url('{static 'home_netflix.jpg'}')"> <div class="flex flex-wrap justify-center w-10/12 md:w-6/12"> <form method="POST" class="w-full md:w-8/12 bg-gray-900 p-5 rounded-lg"> <h1 class="text-4xl text-center text-gray-100 font-medium"> Create A Profile </h1> {% csrf_token %} <div class="my-4"> <Label class='text-lg text-gray-200 font-medium mb-3'> Profile Name </Label> <input required class="p-2 bg-gray-500 rounded-sm text-gray-200 outline-none block w-full" type="text" name="name" id="id_name" placeholder="Profile name"> </div> <div class="my-4"> <Label class='text-lg text-gray-200 font-medium mb-3'> Maturity Level </Label> <select class="p-2 bg-gray-500 rounded-sm text-gray-200 outline-none block w-full" name="age_limit" id="id_age_limit" > <option value="All">All</option> <option value="Kids">Kids</option> </select> </div> <div class="flex justify-center items-center"> <button class="px-4 py-2 rounded-md … -
Django model filter based on boolean field
I have a user model which has fields like these, is_active = models.BooleanField() date_joined = models.DateTimeField(auto_now_add=True) resigned_date = models.DateTimeField(blank=True, null=True) Where resigned_date will be None if is_active field is True. If is_active field is False then the resigned_date field will have the date. I think I can explain it. What I want is to queryset of users based on some DATE and is_active field. More clearly I want to get the list of employee that (is active and joined_date is less that or equal to the current date) and (is not active and resigned_date is greater that the current date) The query I have written so far: users = user_models.User.objects.filter( Q( is_active=True, date_joined__month__lte=month, date_joined__year__lte=year, ) & Q( is_active=False, resigned_date__month__gt=month, resigned_date__year__gt=year, ) ) But this is not working. It is not returning any users. How can I achive this? Thanks -
ModuleNotFoundError: No module named 'django_app' with heroku deployement
Hey mentors and senior devs I am now on this issue 5-7 hours trying to solve it, This issue happens during the deployment of my app on digital oceans apps and these are logs that Heroku sent please help me figure it out 2022-10-03T10:37:01.047248352Z [2022-10-03 10:37:01 +0000] [1] [INFO] Starting gunicorn 20.1.0 2022-10-03T10:37:01.048342704Z [2022-10-03 10:37:01 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2022-10-03T10:37:01.048420287Z [2022-10-03 10:37:01 +0000] [1] [INFO] Using worker: sync 2022-10-03T10:37:01.105225067Z [2022-10-03 10:37:01 +0000] [16] [INFO] Booting worker with pid: 16 2022-10-03T10:37:01.121367774Z [2022-10-03 10:37:01 +0000] [16] [ERROR] Exception in worker process 2022-10-03T10:37:01.121405181Z Traceback (most recent call last): 2022-10-03T10:37:01.121410503Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-10-03T10:37:01.121414404Z worker.init_process() 2022-10-03T10:37:01.121419137Z File "/workspace/.heroku/python/lib/python3.10/site-``` packages/gunicorn/workers/base.py", line 134, in init_process 2022-10-03T10:37:01.121423724Z self.load_wsgi() 2022-10-03T10:37:01.121428153Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-10-03T10:37:01.121431187Z self.wsgi = self.app.wsgi() 2022-10-03T10:37:01.121434180Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/base.py", line 67, in wsgi 2022-10-03T10:37:01.121438157Z self.callable = self.load() 2022-10-03T10:37:01.121441663Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-10-03T10:37:01.121462270Z return self.load_wsgiapp() 2022-10-03T10:37:01.121465690Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-10-03T10:37:01.121469061Z return util.import_app(self.app_uri) 2022-10-03T10:37:01.121472387Z File "/workspace/.heroku/python/lib/python3.10/site- packages/gunicorn/util.py", line 359, in import_app 2022-10-03T10:37:01.121475619Z mod = importlib.import_module(module) 2022-10-03T10:37:01.121482753Z File "/workspace/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2022-10-03T10:37:01.121486027Z return _bootstrap._gcd_import(name[level:], package, level) 2022-10-03T10:37:01.121490349Z File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2022-10-03T10:37:01.121493850Z File "<frozen importlib._bootstrap>", … -
Only id is returing in nested serializer django rest framework
I have two models user and notes, my aim is to get a JSON response like this. { "status": 200, "data": [ { "id": 1, "note": "dd", "created_on": "2022-10-03T06:58:33.337137Z", "is_active": true, "created_by":[{ "username":"loream", "email":"username@gmail.com", ........... } ] }, ]} Modals are : class Notes(models.Model): note= models.TextField() created_on=models.DateTimeField(auto_now_add=True) is_active=models.BooleanField(default=True) user=models.ForeignKey(UserModal,on_delete=models.CASCADE,null=True,related_name="created_byy",blank=True) class UserModal(AbstractUser): username = models.CharField(max_length=30,unique=True) password = models.CharField(max_length=30) email = models.EmailField(blank=True) serializers I wrote is class UserSerializer(serializers.ModelSerializer): class Meta: model = UserModal fields = '__all__' class NotesSerializer(serializers.ModelSerializer): created_byy = UserSerializer(many=True,read_only=True) class Meta: model=Notes fields='__all__' But I couldn't get a JSON response as expected I'm getting responses like this { "status": 200, "data": [ { "id": 1, "note": "dd", "created_on": "2022-10-03T06:58:33.337137Z", "is_active": true, "user": 1 }, ] } how can I achieve the expected result? -
Django web Application to put on VPS or Containers
We have a Django web Application in our workplace running in a local server, and we want to go cloud virtualization. what's the best solution for us: google VPS or containers ? -
Cannot connect to external PostgreSQL database from dockerized Django
I am running Django application dockerized and trying to connect to PostgreSQL database that is located at external host with a public IP. When running a container, makemigrations command falls with the following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "myhost" (89.xx.xx.102) and accepting TCP/IP connections on port 5432? However, it successfully connects when not dockerized. Here the docker-compose.yml: services: backend: build: . ports: - 65534:65534 and corresponding Dockerfile: FROM python:3.10 AS builder ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY requirements.txt /app/ RUN pip install -r /app/requirements.txt RUN pip install gunicorn FROM builder COPY ./ /app/ ENTRYPOINT [ "/app/entrypoint.sh" ] and entrypoint.sh: #!/bin/bash python /app/manage.py collectstatic --no-input --clear python /app/manage.py makemigrations python /app/manage.py migrate --no-input gunicorn --pythonpath /app/ -b 0.0.0.0:65534 app.wsgi:application How to make it possible for the Django application to connect to externally hosted PostgresSQL database? -
Got AttributeError 'User' object has no attribute 'password1'
How to fix the error please help?Got AttributeError 'User' object has no attribute 'password1'. i want to add two password fields. user is created but error occurs AttributeError: Got AttributeError when attempting to get a value for field password1 on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'password1'. views.py class RegisterAPIView(generics.CreateAPIView): serializer_class = UserSerializer queryset = User.objects.all() serializers.py class UserSerializer(serializers.Serializer): username = serializers.CharField( label="Имя пользователя", style={"input_type": "username"} ) email = serializers.CharField( label="почта", style={"input_type": "email"} ) password1 = serializers.CharField( label="Пароль", style={'input_type': 'password'} ) password2 = serializers.CharField( label="Пароль повторно", style={'input_type': 'password'} ) def create(self, validated_data): password1 = validated_data.pop('password1') password2 = validated_data.pop('password2') print(validated_data) if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") validated_data["password"] = password1 print(validated_data) user = User.objects.create(**validated_data) print(user.id) return user -
How to use regex in form.py in django
I am working on Django project. I a fetching the data from POSTgresql in form.py while fetching the data is comming in ('Shirur'), in such format but i want the data as Shirur. Taluka1=forms.ModelChoiceField(queryset=data.objects.values_list("taluka").distinct()) Gut_Number = forms.ModelChoiceField(queryset=data.objects.all().values("gut_number").distinct()) Village_Name_Revenue = forms.ModelChoiceField(queryset=data.objects.all().values("village_name_revenue").distinct()) above is my code '