Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. How to implement a logic to initiate a delete time counter or countdown in django models to delete objects automatically?
Hello guys how can I implement a logic in django to delete a coupon automatically after 2 days from the time the user has opted to delete his post.? I have this view which has the normal delete function. but how to make changes in this to have this deleted automatically after 2 or 3 days from the database and not immediately.? view class DeletePostView(LoginRequiredMixin, UserPassesTestMixin, BSModalDeleteView): model = Post template_name = 'posts/delete_post.html' success_message = 'Deleted' def get_success_url(self): return reverse_lazy('posts:myhome') def test_func(self): post = self.get_object() if self.request.user == post.user: return True return False If its difficult to implement in class based view, please do let me know how to implement that logic with fbv. Thanks -
Django : handle post JSON requests
I need to handle some JSON data with django. I will receive this data : deliveryDay: '2020-06-30', deliveryAddress: 'Place des Fêtes', comment: '', products: [ { id: '420', byProducts: [ { id: '420161', quantity: 42, }, ], }, ], I would like to save this data in 3 differents table: order and orderDetail. models.py: class order(models.Model): user = models.ForeignKey(memberArea, on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) orderDay = models.DateTimeField(auto_now_add=True) deliveryDay = models.DateField() deliveryPlace = models.CharField(max_length=255) state = models.CharField(max_length=255) price = models.TextField(null=True, blank=True) response = models.TextField(null=True, blank=True) ... class orderDetail(models.Model): order = models.ForeignKey(order, on_delete=models.CASCADE) product = models.ForeignKey(product, on_delete=models.CASCADE) byProduct = models.ManyToManyField(byProduct) quantity = models.CharField(max_length=255) I don't find any documentation about how to handle JSON data whith Django. Thanks by advance -
Images not showing when running for loop to fetch images
I have a for loop in my index.html file to dynamically fetch images from the images folder for three objects. But it is only fetching the first image, with that missing image icon showing on the server for the other two 'destination' objects. Is there anything standing out as amiss in the index.html and views.py files? All three images were showing when they were hardcoded and are all present in the images folder. It's since I introduced the {% static "images" as baseUrl %} and the for loop that it doesn't work. It's just odd that it does indeed load the first image, but not image 2 and image 3. Here is the for loop code with the top imports in index.html: {% load static %} {% static "images" as baseUrl %} {% for dest in dests %} <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{baseUrl}}/{{dest.img}}" alt=""> <div class="spec_offer text-center"><a href="#">Special Offer</a></div> </div> <div class="destination_content"> <div class="destination_title"><a href="destinations.html">{{dest.name}}</a></div> <div class="destination_subtitle"><p>{{dest.desc}}</p></div> <div class="destination_price">From ${{dest.price}}</div> </div> </div> {% endfor %} In my views.py file: from django.shortcuts import render from .models import Destination def index(request): dest1 = Destination() dest1.name = 'New York' dest1.desc = 'City that never sleeps' dest1.img = 'destination_1.jpg' … -
AsserrtTemplateUsed fails despite template being used...?
I have a view: class DashboardView(TemplateView): template_name = "dashboard/dashboard.html" Which I am testing using TestCase: class TestAuthorisedViews(TestCase): @classmethod def setUpTestData(cls): cls.client = Client() cls.response = cls.client.get(cls.url) def test_view_uses_correct_template(self): print('template', self.response.__dict__) self.assertTemplateUsed(self.response, 'dashboard/dashboard.html') This test fails with AssertionError: No templates used to render the response. However, the print() debug I included in the test reveals the response does use a template: template {'template_name': ['dashboard/dashboard.html'], 'context_data': { 'view': <dashboard.views.DashboardView object at 0x0000019E9CF33040> }, // etc >} Am I using this test correctly? When looking at the source code, it seems the error fails because response.templates = [] rather than response.templates = None. -
Page not found http://127.0.0.1:8000/manageAccount/a/delete
I dont know why show this page because i think all work is right i coudln't identifying why throw this error anyone tell me so please tell me how i solve this issue .................................................................................................................................................................................... template.html <a href="{{ request.user }}/delete" class="ml-4">Delete Account</a><Br> urls.py path('<str:username>/delete', delete_user, name='delete-user'), views.py def delete_user(request, username): context = {} u = User.objects.get(User,username=username) u.delete() messages.success(request,'your account delete') return render(request, 'home/login.html', context=context) -
Python setup.py "End of statement expected"
I'm getting a syntax error in PyCharm in the last line of my setup.py file: "end of statement expected". This is for a Django application. What am I missing? Note: This is the first setup.py file I've created. #!/usr/bin/env python from setuptools import setup, find_packages setup(name='myproject', version='1.0', packages=find_packages()), scripts=['manage.py']) I've tried: ... scripts=['manage.py']), ) Nope. I've tried: ... scripts=['manage.py']) ) Nope, what? Please help. -
"POST" being send but it return "GET"
enter image description here enter image description herer.com/ezYur.png path('dash_board/enter_farmer_details/',views.enter_farmer_details,name='enter_farmer_details'), -
save() missing 1 required positional argument 'self'
This is view: def add_bus_save(request): if request.method=="POST": Type=request.POST.get("Type") Number_of_Seats=request.POST.get("Number_of_Seats") driver=request.POST.get("driver") hostess=request.POST.get("hostess") manager_id=request.POST.get("manager_id") staff_id=request.POST.get("staff_id") if driver.isalpha()==False: messages.error(request, 'Enter name of valid alphabets') return redirect('add_bus') elif hostess.isalpha()==False: messages.error(request, 'Enter name of valid alphabets') return redirect('add_bus') else: try: bus.Type=Type bus.Number_of_Seats=Number_of_Seats bus.driver=driver bus.hostess=hostess manager_obj1=Manager.objects.get(id=manager_id) bus.manager_id=manager_obj1 staff_obj1=Staff.objects.get(id=staff_id) bus.staff_id=staff_obj1 bus.save() #Error messages.success(request,"Successfully Added Bus") return HttpResponseRedirect(reverse("add_bus")) except: messages.error(request,"Failed to Add Bus") return HttpResponseRedirect(reverse("add_bus")) else: return render(request, 'add_bus.html') I want to save bus.save() to mysql,But it gives me an error on bus.save(), TypeError: save() missing 1 required positional argument: 'self',How should I solve it? -
Django AbstracUser with multiple profiles
I'm having a given below models.py structure: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models class User(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD = "email" email = models.EmailField(verbose_name="E-mail", unique=True) def __str__(self): return self.email class Profile(models.Model): phone_number = models.CharField(verbose_name="Phone number", max_length=15) def __str__(self): return self.phone_number class Meta: abstract = True class UserProfile(Profile): user = models.ForeignKey(to=User, on_delete=models.PROTECT, related_name="profile") group = models.CharField( verbose_name="Group type", choices=GroupChoices.choices(), # Group1, Group2 etc. max_length=20 ) def __str__(self): return self.user class Meta: unique_together = ("user", "group") I'd like to have a possibility to create users with the same email & phone number. The only difference would be a membership to different groups. The code below seems to be working properly, but once there are two users with the same email(which makes user instance unique), it always returns a list of profiles, instead of returning the specific user profile. One of the concerns is when accessing another model where User model is in a relation by FK. Then it returns a list of profiles, instead of the specific one. To compare, using Uber app you can be both a passenger & driver (the same email and the same phone number, but different profiles) - I'm trying to achieve something similar. Is this … -
ModuleNotFoundError: No module named 'chefsBackEnd.wsgi' Django RF API Deploying with Heroku and Gunicorn
I am attempting to deploy my api to heroku. The api uses PIPENV as the virutal env; Django Rest Framework. When I deploy to heroku, I get the following logs: ModuleNotFoundError: No module named 'chefsBackEnd.wsgi'. After doing some research, I found that the name of application goes before .wsgi. The information showed to set up in Procfile writing exactly: web: gunicorn chefsBackEnd.wsgi --log-file - Here is my settings.py for django: import os import django_heroku # import cloudinary # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p%s-9w1l268@!b$p#92dj26q)pv7!&ln^3m(1j5#!k8pkc9@(u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['mock-chefs-table-api.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 'allauth', # 'allauth.account', # 'allauth.socialaccount', 'corsheaders', # 'pyuploadcare.dj', # 'cloudinary', # 'rest_auth', # 'rest_auth.registration', 'rest_framework', # 'rest_framework.authtoken', 'menus', # 'phlogfeeder', 'login', # 'posts', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chefsBackEnd.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
I'm getting this error in django using pycharmenter image description here I'm following this tutorial " https://www.youtube.com/watch?v=OTmQOjsl0eg " at static 2 around 1:18:00 I have also shared the screenshot DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/styles/bootstrap4/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE Please guys help me solve this -
Using Redirect to access generated URL
I intend rerouting to a URL generated in my view. I'm trying to use redirect but it throws: 'localhost' is not a registered namespace in my local server. I need the functionality of auto generating this URL so i won't hardcode in production. class SignUp(FormView): template_name = 'blogApi/tenant_registration.html' form_class = ClientForm def get(self, request, *args, **kwargs): form = ClientForm() context = {'form': form} return render(request, 'blogApi/tenant_registration.html', context) def form_valid(self, form): name = form.cleaned_data['name'] url = self.request.get_host() print(name+"."+url) Client.objects.create(name=name, schema_name=name, domain_url=name+".localhost") return redirect(url) urls.py from django.urls import path, include from .views import SignUp urlpatterns = [ path('signup/', SignUp.as_view(), name="sign_up"), path('home', include('blogApi.urls', namespace="blog"), name='home'), ] -
Write Admin Messages in Bearle / Django-Private-Chat (Django 2/Python)
I was wondering, if it is possible to connect (as an admin) with a user and to write messages? I already modified the message-table in the database, however, the message does only appear after reloading the whole website - which is not the optimal outcome. I appreciate every hint. Thank you. -
IntegrityError: update or delete on table "products_product" violates foreign key constraint
I am trying to delete from Django admin all the products which are stored in PostgresSQL database but getting that error for one product: IntegrityError at /admin/products/product/ update or delete on table "products_product" violates foreign key constraint "products_curateprodu_product_id_ec2cf1ec_fk_products_" on table "products_curateproducts_products" DETAIL: Key (id)=(72) is still referenced from table "products_curateproducts_products". I am not able to figure out why it shows that error while under Curranted Products in Django admin I don´t have any products. At least it won´t show there any, just 0 Curated Products. Code is here for the Product model: class Product(models.Model): seller = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) media = models.ImageField(blank=True, null=True, upload_to=download_media_location, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)) title = models.CharField(max_length=150) slug = models.SlugField(blank=True, unique=True) description = models.TextField(max_length=200, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=9.99, null=True) sale_active =models.BooleanField(default=False) sale_price = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True) def __str__(self): return self.title class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' ordering = ['title'] and code for Curated Products model: class CuratedProducts(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) section_name = models.CharField(max_length=20, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) active = models.BooleanField(default=True) def __str__(self): return self.section_name class Meta: verbose_name = 'Curated Product' verbose_name_plural = 'Curated Products' -
ImageField is not uploading to specified directory
I have been googling this for an ours and can't find the solution. When I use admin panel, image is loading to the directory that is needed. But when I create post from the fronend, the image is just loading to the main directory, wich is media. I now that I it will work if I use django forms and createview, but I need adding a post with a function like I did. I think this problem might happen, because ImageField needs validating. But I don't know how to validate it outside the django forms context. Any help appreciated. I have model Posts with ImageField image and upload_to option: class Posts(models.Model): image = models.ImageField(upload_to="posts/%Y/%m/%d", null=True,blank=True) then in views.py the function, that adds new post: @login_required def add_post(request): if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') upload_file = request.FILES['image'] fs = FileSystemStorage() image = fs.save(upload_file.name, upload_file) post = Posts(title=title, content=content, image= image) post.author = request.user post.save() from django.http import HttpResponseRedirect #return redirect(post.get_absolute_url()) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return render(request ,'users/user-detail2.html') and the wich displays the form: <form action="{% url 'add_post' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Share Your Mood</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div … -
How to use a Many-to-Many through model in DRF
So I'm trying to achieve the general "Like" functionality in a social media website using Django and REST Framework, and a frontend in React. Using a Post model to save all the posts, and I have a Many-to-Many field for storing the likes and created a through model as follows: class PostLike(models.Model): user = models.ForeignKey(AppUser, on_delete=models.CASCADE) post = models.ForeignKey("Post", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(AppUser, on_delete=models.CASCADE) caption = models.TextField() created_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField( AppUser, related_name="post_user", blank=True, through=PostLike ) (AppUser is a custom auth model used) Similarly, I have created serializers and viewsets for the above models: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" class PostLikeSerializer(serializers.ModelSerializer): class Meta: model = PostLike fields = "__all__" class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer class PostLikeViewSet(viewsets.ModelViewSet): queryset = PostLike.objects.all() serializer_class = PostLikeSerializer My question is, how do I "like" or remove an existing "like" from a post using API calls? One method I know is to just make a POST request to the PostLike endpoint using the user PK and the post PK to create a PostLike instance, but I don't know a way to "remove" a like using the same method. … -
Connecting PostgreSQL db to Django project using Docker
I have a problem connecting my Postgres database to django project on docker container. I have already tried every solution found on the internet and nothing seems to work. I've already added host all all all md5 to my pg_hba.conf file, listen_addresses = '*' to postgresql.conf. Here is log from lsof -i :5432: postgres 19774 postgres 5u IPv4 2046377 0t0 TCP *:postgresql (LISTEN) postgres 19774 postgres 6u IPv6 2046378 0t0 TCP *:postgresql (LISTEN) I've tried to open 5432 port by using ufw allow 5432/tcp, it seems to be open. My docker-compose.yml file: version: '3.8' services: db: image: postgres:12.0-alpine environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_DB: ${POSTGRES_DB} build: . container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ networks: - djangonetwork ports: - '5432' web: build: context: . dockerfile: Dockerfile command: python manage.py runserver 127.0.0.1:8000 volumes: - ./TwitterClone/:/usr/src/TwitterClone/ ports: - 8000:8000 env_file: - ./.env depends_on: - db links: - db:db networks: - djangonetwork networks: djangonetwork: driver: bridge volumes: postgres_data: settings.py: try: DATABASE_PASSWORD = os.environ.get('POSTGRES_PASSWORD') DATABASE_USER = os.environ.get('POSTGRES_USER') DATABASE_NAME = os.environ.get('POSTGRES_DB') except: print('Could not get environment variables') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DATABASE_NAME, 'USER': DATABASE_USER, 'PASSWORD': DATABASE_PASSWORD, 'HOST': '127.0.0.1', 'PORT': 5432, } } No matter what I try to do, I always end up … -
Is it possible to stream JSON in Django with StreamingHTTPResponse or in any other way?
I'm wondering if it's possible to correctly stream JSON in Django? I've tried to use StreamingHTTPResponse but what I'm sending is incorrect JSON format - expected [json], sending [json][json]..[json], each is separate array. I kind of understand the idea - we cannot send [json ... json... json] because it will be incomplete on all iterations but last (it's important to close the array bracket). But maybe I'm wrong. Please help me to understand how JSON can be streamed correctly. According to documentation StreamingHTTPResponse mostly used for csv, but nowhere is it said that it cannot be used for JSON. If that's the case, how to make it work? Would really appreciate any help, I'm trying to solve this mystery for a few days now. def generator_chunk(): ... yield df.to_json # returns data like [json] @api_view(['GET']) def return_data(request): ... return StreamHttpResponse(generator_chunk) # streams data like [json][json], which is not proper json format Similar questions (which have no answer): Proper way of streaming JSON with Django django stream a dictionary multiple times w/o breaking JSON -
django, celery do not update database
firstly, I'm new on celery, django, even python. I wanna update my database(sqlite, default database on django). but my code didn't work. Project name is Hcloset. crawl_periodically is app in Hcloset. celery.py and tasks.py are in crawl_periodically. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Hcloset.settings') app = Celery('crawl_periodically', broker='django://') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import task from fashion.models import SelectShopSite @task(name='crawl') def test(): sss = SelectShopSite(site_name='temp', site_main_url='https://') sss.save() print(4*5000) part of settings INSTALLED_APPS = [ 'crawl_periodically.apps.CrawlPeriodicallyConfig', 'django_crontab', 'django_celery_results', .... ] ... CELERY_RESULT_BACKEND = 'django-db' # celery things from celery.schedules import crontab CELERY_BROKER_URL = 'pyamqp://guest@localhost//' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_BEAT_SCHEDULE = { 'send-summary-every-hour': { 'task': 'summary', 'schedule': 5.0, }, 'send-notification-on-friday-afternoon': { 'task': 'my_app.tasks.send_notification', 'schedule': crontab(hour=16, day_of_week=5), }, } celery -A crawl_periodically beat -l DEBUG it is running well... but database is not updated. what can i do?.... -
django error: cart.js:4 Uncaught TypeError: updateBtns[i].addEventListner is not a function at cart.js:4
I have never worked with js until now and i keep getting this error cart.js:4 Uncaught TypeError: updateBtns[i].addEventListner is not a function at cart.js:4 I have searched it and none of the answers that i used helped. cart.js var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListner('click', function(){ var productId = this.dataset.products var action = this.dataset.action console.log('productId: ', productId, 'action: ', action) }) } store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <form method="GET" action="."> <div class="row"> <div class="column"> <button type='submit' class='btn btn-primary btn2'>Search</button> </div> <div class="column"> <input type="text" name="search" class="form-control" placeholder="search" /> </div> </div> </form> </div> <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{ product.imageURL }}"> <div class="box-element product"> <h6><strong>{{ product.name }}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><strong>R{{ product.price|floatformat:2 }}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} part of store.html <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> i am using python django and trying to make a cart system for my ecom store -
Ajax not updating the div in Django
I'm using Ajax for like button in my Blog. When I hit Like button, the count is updated in DB but it is not reflecting in my page(The button should change to 'Unlike' without reloading the page). But, when i refresh the page, it is reflecting as expected. views.py: def like_post(request): user = request.user post_id = request.POST.get('id') post_obj = get_object_or_404(Post, id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context={ 'post': post_obj } if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) Ajax: <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type : 'POST', url : {% url 'like-post' %}, data : {'id' : pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : 'json', success : function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])); }, error : function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> Html: <form action="{% url 'like-post' %}" method="POST"> {% csrf_token %} {% if user not in post.liked.all %} <button id="like" name="post_id" value="{{ post.id }}" class="btn btn-outline-info mb-4" type="submit">Like</button> {% else %} <button id="like" name="post_id" value="{{ post.id }}" class="btn btn-info mb-4" type="submit">Unlike</button> {% endif %} </form> … -
initdb: error: could not create directory “./PostgreSQL”: Permission denied
It is my first time setting up a database (postgresql 12) on my windows 8.1 It's been 4 days of struggling to find a solution from many related questions in this field but not successful to find the answer (whether I didn't understand them or they didn't work in my case). So, here, I will explain, step by step, what I did and what errors I got in each phase (They may not affect each other but I mention all the errors): When I installed PostgreSQL, at the end of the process I got this error: "Failed to load SQL modules into the database cluster" I reinstalled twice but it seemed to pop up every time. Here, in this post, I found somebody who faced the same problem, but I didn't technically understand what is the solution, unfortunately: Failed to load sql modules into the database cluster during PostgreSQL Installation. thus, I just skipped it and everything seemed okay. Then I set the PATH in advanced system settings-->Environment variables (in both user variables and system variables boxes) like this: ";C:\Program Files\PostgreSQL\12\bin;C:\Program Files\PostgreSQL\12\lib" After this step, I opened a terminal using ctrl+R and entered cmd.exe then entered these codes: > cd … -
Django : profile edition set_password()
I would like to create an API for a mobile application. In this application, we can create an account, and of course, edit our profile. For create an account, I use the django account default model like that: models.py: def create_user(self, email, username, phone, deliveryAddress, postalCode, city, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError('Users must have an username') if not phone: raise ValueError('Users must have a phone number') if not deliveryAddress: raise ValueError('Users must have a delivery Address') if not postalCode: raise ValueError("Users must have a postal code") if not city: raise ValueError('Users must have a city') user = self.model( email = self.normalize_email(email), username = username, phone = phone, deliveryAddress = deliveryAddress, postalCode = postalCode, city = city, ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email, username, phone, deliveryAddress, postalCode, city, password=None): user = self.create_user( email = self.normalize_email(email), username = username, password = password, phone = phone, deliveryAddress = deliveryAddress, postalCode = postalCode, city = city, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self._db) class memberArea(AbstractBaseUser): username = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) phone = models.TextField() date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last … -
Django Form Fields arent displayed
I want to display to simple search Forms in a view. forms.py: from django import forms from django.utils.translation import gettext_lazy as _ class Vehicle_Search_by_VIN(forms.Form): vin = models.CharField(max_length=17) first_registration_date = models.DateField() class Vehicle_Search_by_Plate(forms.Form): plate = models.CharField(max_length=7) last_four_diggits_of_vin = models.DateField(max_length=4) views.py: from django.shortcuts import render from django.views import View from .forms import * class VehicleSearch(View): template = 'vehicle_search_template.html' cxt = { 'Search_by_VIN': Vehicle_Search_by_VIN(), 'Search_by_Plate': Vehicle_Search_by_Plate() } def get(self, request): return render(request, self.template, self.cxt) my template-file: <form class="by_vin" method="POST" action=""> {% csrf_token %} {{ Search_by_VIN.as_p }} <button name='action' value='login' type="submit">Suchen</button> </form> <form class="by_plate" method="POST" action=""> {% csrf_token %} {{ Search_by_Plate.as_p }} <button name='action' value='signup' type="submit">Suchen</button> </form> But as a result only the submit buttons are displayed in the view. Does anybody know why my forms aren't being rendered? -
How to fix The QuerySet value for an exact lookup must be limited to one result using slicing?
I am trying to get count with syntax : count = Comment.objects.filter(blog=blog).count()