Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
server Python Django
How to accept data from the client using a Post request (Login, password, email) with subsequent entry into the database for use when logging in I used it, but I don't fully understand it correctly or not, most likely not because nothing is written to the database Views.py class Reqs: def __init__(self, user, password, email): self.user = user self.password = password self.email = email class ReqsEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Reqs): return { "user": obj.user, "password": obj.password, "email": obj.email, } return super().default(obj) def api_response(request): user = request.POST.get("user") password = request.POST.get("password") email_ = request.POST.get("email") data = Data(user, password, email_) data.save() try: return HttpResponse(data, safe=False, encoder=ReqsEncoder) except: return HttpResponse("G") -
getting error while save image to db using s3 bucket
RuntimeError: Input Screenshot from 2022-12-23 18-34-04.png of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported. getting this error while use s3 bucket in django InMemoryUploadedFile error -
how to create dependent dropdown list in CRUD Django
I am beginner and trying to create CRUD Django Application where I want to keep below fields. Company Name DOB Date and time State (should be dependency between State and City) City (should be dependency between State and City) Please help me for complete code For example i give input as company name : ABC DOB Date and time : 2022-01-01 08:12:00 State : Karnataka(if I select State "Karnataka" then related city of Karnataka has to be showed in dropdown) City : Bangalore, Mysore ''''''''''''''''' if I click on edit button entire field's value has to be show form design has to horizonal for Example company name DOB , Date and time State , City Not like this company name DOB Date and time State City -
Three-level inline formsets in the frontend
I'm trying to accomplish a three-level stacked inline form in Django. Suppose these models: class Anuncio(models.Model): title = models.CharField(max_length=200) delivery = models.CharField(max_length=100) class Product(models.Model): anuncio = models.ForeignKey(Anuncio, on_delete=models.CASCADE) name = models.CharField(max_length=200) quantity = models.PositiveIntegerField(default=1) price = models.PositiveIntegerField() class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField() There is a relation Anuncio-Product and another relation Product-Image. With this Django package, I accomplished exactly what I want in the Django admin: when creating an Anuncio object, I can add as many Products as I want, and those products can have as many Images as I want. I'm trying to accomplish this in the front end. I think the way to go is with Django formsets, but I'm facing some problems. All the resources I've been able to find online are only 'two-level' formsets or in 'three-level' cases all the foreign keys point to the same parent model. With this forms.py file: class ProductForm(ModelForm): class Meta: model = Product fields = ['name', 'quantity', 'price'] class ImageForm(ModelForm): class Meta: model = Imagen fields = ['image'] class AnuncioForm(ModelForm): class Meta: model = Anuncio fields = ['title', 'delivery'] And this views.py function: def anunciocreateview(request): form = AnuncioForm(request.POST or None) ProductFormSet = inlineformset_factory(Anuncio, Product, form=ProductForm) ImageFormSet = … -
Django - How to remove data redundancy from the state model
My following code is storing multiple data: models.py from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.IntegerField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 if Country.objects.filter(name=self.name).exists(): pass else: super().save(*args, **kwargs) class State(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() try: country_obj = Country.objects.get(name=self.name) self.parent_id = country_obj.id except Country.DoesNotExist: pass super().save(*args, **kwargs) My country model is working fine it does not have any issue related to data redundancy/repetition and is storing the data as it is intended. But my state model, either gets parent_id as null or stores the country name again in the database. I have no clue where i am going wrong. Will attach forms.py and views.py for your perusal: forms.py: class CustomerLocationForm(forms.Form): country = forms.ChoiceField(choices=COUNTRY_CHOICES) state = forms.CharField(max_length=100) status = forms.ChoiceField(choices=STATUS_CHOICES) class CustomerCountryForm(forms.Form): country = forms.CharField(max_length=100) status = forms.ChoiceField(choices=STATUS_CHOICES) class Meta: model=customer_location exclude = … -
Django - MySQL intergration Mac M1 Max
I'm relatively new to Django and working on a project. I was about to makemigrations and got the following trace: demoproject lamidotijjo$ python3 manage.py makemigrations Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib Referenced from: <D6AC4B91-4AA0-31A5-AA10-DE3277524713> /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so Reason: tried: '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 22, in <module> main() File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
Tried building a query that would give you the page views per url for a given date range and needs to apply filters
I got the output for the page views per url for a given date range but as it fetches every url i need to apply filters into it for the dimension ga:landingPagePath The output for the query when executed is:- http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html And i only need the pageviews for the landing page starting with /job-details/ I tried giving the filters like:- filters=ga:landingPagePath%3D%3D/job-details/ but i was getting an error like:- Error message: Invalid value 'filters=ga:landingPagePath%3D%3D/job-details/'. Values must match the following regular expression: 'ga:.+' -
Troubleshooting k8s readiness probe failure
I'm trying to run my django rest framework application in k8s environment but readiness probe fails. I wonder how to get what is wrong. When I look at pod logs the app seems to be running. It has unapplied migrations, but it is ok: C:\Users\user>kubectl logs test-bbdccbc76-8cwg9 Watching for file changes with StatReloader Performing system checks... Server initialized for gevent. System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/app/staticfiles' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth Run 'python manage.py migrate' to apply them. December 27, 2022 - 06:13:28 Django version 4.1.2, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Here is describe pod output: C:\Users\user>kubectl describe pod test-bbdccbc76-8cwg9 Name: test-bbdccbc76-8cwg9 Namespace: test Priority: 2000 Priority Class Name: default Service Account: default Node: sd2-k8s-stg-n05/10.216.14.52 Start Time: Tue, 27 Dec 2022 11:11:14 +0500 Labels: app=test pod-template-hash=bbdccbc76 Annotations: checksum/config: f0ee0887d3fd078979831f04d13ade8759ef8a4ee9aad23830c5909300e322b4 cni.projectcalico.org/containerID: ac4c0c57c0a3baa1c15a78aedb36e3e1890f8b9859547807b1e3587835792efb cni.projectcalico.org/podIP: 10.233.110.84/32 cni.projectcalico.org/podIPs: 10.233.110.84/32 container.apparmor.security.beta.kubernetes.io/test: runtime/default kubernetes.io/psp: restricted seccomp.security.alpha.kubernetes.io/pod: runtime/default Status: Running IP: 10.233.110.84 IPs: IP: 10.233.110.84 Controlled By: ReplicaSet/test-bbdccbc76 Containers: test: Container ID: containerd://26e3234ba31c09d6d62e3efb999634cb64d26d6ce2e8e734a26104d62b6f2f5f Image: registry/library/test:latest Image … -
How to communicate two or more microservices in django rest framework?
I have been looking to communicate two or multiple microservices in django and need to make them communicate with each. I've reasearched about it and didnt get proper info about it. what i understood is each microservices application completely dont depend on one another including the database. Now how to communicate each microservices with one another. there are 2 methods **synchronous and asynchronous ** method. i dont want to use synchronous. how to communicate the endpoints of api in asynchronous way? i found some message brokers like rabbitMQ, kafka, gRPc... Which is the best brokers. and how to communicate using those service? i didnt get any proper guidance. I'm willing to learn , can anybody please explain with some example ? It will be huge boost in my work. -
Django APP Spin Wheel with Voucher: UNIQUE CODE with SELECTED PRIZE not working
i have a Django App Spin Wheel with Voucher. the problem is when i generate unique code with selected prize then i spin wheel with generated unique code (eg. prize chosed from admin panel was TV) the spin result wont go to TV, it will go to other prize. PRIZE front view here is my repo link : https://github.com/DracoMalfoy1000/spinproject please i really need help thank you yesterday i added ` prize = models.ForeignKey('Prize', on_delete=models.CASCADE, null=True) ` on my UniqueCode class (models.py) ADD UNIQUE CODE ADMIN PANEL the option added but when i generate code and try to spin, it wont go to the result i chose on admin panel. here is my repo link : https://github.com/DracoMalfoy1000/spinproject please i really need help thank you -
Use Web Crypto API to decrypt ciphertext which was encrypted using the Python pycrytodome library
I am running a django app and I am trying to use a RSA 'challenge' to verify that a user has the correct private key. The keys are generated client side using the js Web Crypto API and the public key is sent to django as a jwk and the private key is stored in a client-side pem file. I want the django view to send an encrypted uuid to the client page where a user has loaded their private key file. Then the page locally decrypts the uuid and sends it back to the server for authentication. It seems like I have gotten everything to work except for the client side decryption. Here is the relevant portion of the django/python view: uuid = secrets.token_hex(16) key = json.loads(request.POST.get('key')) //key is in JWK format e = int.from_bytes(base64.b64decode(base64url_to_base64(key['e'])), "big") n = int.from_bytes(base64.b64decode(base64url_to_base64(key['n'])), "big") rsakey = RSA.construct((n, e), consistency_check=True) cipher = PKCS1_OAEP.new(rsakey) challenge = cipher.encrypt(uuid.encode()) Here is the relevant portion of the client-side js: fileReader.readAsText(file); fileReader.onload = function() { filekey = fileReader.result; filekey = filekey.substring(filekey.indexOf('-----BEGIN PRIVATE KEY-----')); let pem = filekey; const pemHeader = "-----BEGIN PRIVATE KEY-----"; const pemFooter = "-----END PRIVATE KEY-----"; const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length); const binaryDerString = … -
Stringed Boolean Search or Filter in Django
I have a user model with first_name and last_name in it. Suppose there are the data in it: ID first_name last_name 1 FightWith Code 2 Jon Doe 3 John Cena And another model with Address with following data: ID user City 4 1 Ohio 5 2 Delhi 6 3 London I want to search them based on their fields, these fields like first_name and city or last_name and city using Boolean Search technique like following: John AND (Ohio OR London) or Jon OR John AND (Delhi OR London) Some what similar to those. I am sure we can do this using Q from django.db.models and operator module but I am not sure how. Has anyone done this and can guide to do the same here then that would be awesome. -
How to add ellipses on function based django paginator
I have a model on database . I am pushing data to the database and making query as well. As the data is growing large its time to use pagination to get better user experience . now pagination is added with the page number along with next and previous button. But the problem is while data become larger the page number increases as well which doesn't cool to me . I wanna add ellipses with the pagination navbar so that only few number will be shown on the navbar and rest will be hidden with ellipses views.py def VideoList(request): vid_mi=Video.objects.all() filter=VidFilter(request.GET,queryset=vid_mi) paginator=Paginator(filter.qs,10) page_num=request.GET.get('page') page_obj=paginator.get_page(page_num) num= "a" * page_obj.paginator.num_pages context={ "filter":filter, "page_obj":page_obj, "nums":num } return render(request,'adminlte/videoList.html',context) html {%if page_obj.has_next or page_obj.has_previous%} <nav aria-label="..." style="float:right;"> <ul class="pagination"> {%if page_obj.has_previous%} <li class="page-item "> <a class="page-link" href="?page={{page_obj.previous_page_number}}" >Previous</a> </li> {% else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">Previous</a> </li> {% endif%} {% for i in nums%} <li class="{% if forloop.counter == page_obj.number%}page-item active{%endif%}"><a class="page-link" href="?page={{forloop.counter}}"> {{forloop.counter}} </a></li> {% endfor%} {%if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="?page={{page_obj.next_page_number}}">Next</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#">Next</a> </li> {% endif%} </ul> </nav> {% endif%} -
How to solve django.db.utils.OperationalError: (1050, "Table '###' already exists") error when running tests in Django
I am working with django.test package in my project, and have implemented some testcases. I have a MySQL database, and have created a test database with no problem. But now when I am running my tests it shows the below error. Type 'yes' if you would like to try deleting the test database 'test_sepantadb', or 'no' to cancel: Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_sepantadb'; database exists") And after I type yes to the console, it shows the below errors, and I don't know how to solve them. Destroying old test database for alias 'default'... Traceback (most recent call last): File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "D:\ABDAL\SepantaEnv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 148, in execute result = self._query(query) File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\cursors.py", line 310, in _query conn.query(q) File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result result.read() File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 1156, in read first_packet = self.connection._read_packet() File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet packet.raise_for_error() File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "D:\ABDAL\SepantaEnv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1050, "Table 'react_arimapredictedvalues' already exists") I have … -
how to pass the Integrity error django and DRF without stoping execution raising the error
I am byulding an API using django and DRF my code is this models.py class Company(models.Model): """Company object.""" name_company = models.CharField(max_length=255) symbol = models.CharField(max_length=10, unique=True) cik = models.CharField(max_length=150, blank=True) sector = models.CharField(max_length=150, blank=True) industry_category = models.CharField(max_length=150, blank=True) company_url = models.TextField(blank=True) description = models.TextField(blank=True) def __str__(self): return self.name_company views.py class CompanyViewSet(viewsets.ModelViewSet): """View for manage company APIs.""" serializer_class = serializers.CompanyDetailSerializer queryset = Company.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_serializer_class(self): """Return the serializer class for request.""" if self.action == 'list': return serializers.CompanySerializer return self.serializer_class def perform_create(self, serializer): """Create a new Company.""" try: serializer.save() except IntegrityError: print('Symbol exists already.') pass serializers.py class CompanySerializer(serializers.ModelSerializer): """Serializer for Company.""" class Meta: model = Company fields = [ 'id', 'name_company', 'symbol', 'cik', 'sector', 'industry_category', 'company_url', ] read_only_fields = ['id'] def create(self, validated_data): try: instance, created = Company.objects.get_or_create(**validated_data) if created: return instance except IntegrityError: pass class CompanyDetailSerializer(CompanySerializer): """Serializer for Company details.""" class Meta(CompanySerializer.Meta): fields = CompanySerializer.Meta.fields + ['description'] And right now i am doing unit tests using in this file. test_company.py def create_company(**params): """Create and return a sample company.""" defaults = { 'name_company': 'Apple', 'symbol': 'AAPL', 'cik': '0000320193', 'sector': 'Technology', 'industry_category': 'Consumer Electronics', 'company_url': 'https://www.apple.com/', 'description':'', } defaults.update(params) company = Company.objects.create(**defaults) return company def test_retrieve_companies(self): """Test retrieving … -
How can I define Model ViewSet for Contact Form that sends email in django-rest-framework?
I have a APIView for a Contact that takes input data from user and send it to mail: from django.core.mail import send_mail class ContactView(APIView): serializer_class = ContactSerializer def post(self, request, *args, **kwargs): serializer_class = ContactSerializer(data = request.data) if serializer_class.is_valid(): data = serializer_class.validated_data name = data.get('name') email = data.get('email') message = data.get('message') send_mail('Contact Form Mail from ' + name, message, email, ['bibekjoshi34@gmail.com'],) return Response({"success":"sent"}, status=status.HTTP_200_OK) else: return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('contactapi', views.ContactView.as_view()), ] Question: Now my question is: How can I do it using DRF ModelViewset. This below code isn't working. class CustomerContactViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Contact.objects.all() http_method_names = ['post'] serializer_class = ContactSerializer def post(self, request): serializer_class = ContactSerializer(data=request.data) if serializer_class.is_valid(): data = serializer_class.validated_data full_name = data.get('full_name') email = data.get('email') phone_no = data.get('phone_no') message = data.get('message') send_mail('Mail From' + full_name, phone_no, message, email, ['bibekjoshi34@gmail.com'],) return Response({"success":"sent"}, status=status.HTTP_200_OK) else: return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST) Please Suggest If there is any best way to make contact-form: that stores data in database as well as sends to the admin mail: --------> For Production Level -
Django - "Field 'parent_id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x00000246709F8590>."
i am trying to set the parent id of state as country's auto incremented id but i am having the described error: I want my database to look like: The country's parent id should be 0 whereas, the state's parent_ id should be country's id. Please help community This is my models.py class customer_location(models.Model): parent_id=models.IntegerField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.parent_id = 0 super().save(*args, **kwargs) class State(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.parent_id = Country.id super().save(*args, **kwargs) My views.py def add_customer_state(request): if request.method == 'POST': form = CustomerStateForm(request.POST) if form.is_valid(): country = form.cleaned_data['country'] state = form.cleaned_data['state'] status = form.cleaned_data['status'] country_obj = Country(name=country, status=status) country_obj.save() state_obj = State(name=state, parent_id=country_obj.id, status=status) state_obj.save() return redirect('success') else: form = CustomerStateForm() return render(request, 'add_customer_state.html', {'form': form}) def success_view(request): return render(request, 'success.html') forms.py class CustomerStateForm(forms.Form): country = forms.CharField(max_length=100) state = forms.CharField(max_length=100) status = forms.ChoiceField(choices=STATUS_CHOICES) def save(self): country = Country.objects.get(name=self.cleaned_data['country']) state = State(name=self.cleaned_data['state'], status=self.cleaned_data['status'], country=country) state.parent_id = country.id state.save() -
How to reuse database in some tests using `pytest-django`?
According to the documentation, --reuse-db should be used or addopts = --reuse-db in pytest.ini. I tried both and they don't work. The current tests have to signup and authenticate a new user at the start of each test to be able to access features requiring login. This makes tests run slowly and with the number of tests growing, this is becoming less convenient. Here's an example to demonstrate: @pytest.mark.django_db class TestSignIn: def test_valid_user(self, client, valid_user_data, django_user_model, django_db_keepdb): client_signup(client, valid_user_data, django_db_keepdb) response = activate_user(client) assert 'sign out' in get_text(response) def test_sign_in(self, client, valid_user_data, django_user_model, django_db_keepdb): client_signup(client, valid_user_data) activate_user(client) response = client.post(reverse('signout'), follow=True) assert 'sign in' in get_text(response) response = client_sign_in(client, valid_user_data) assert 'sign out' in get_text(response) In test_valid_user, a new user is created and after user activation, a user shows up: >>> django_user_model.objects.count() 1 and I verify using: >>> django_db_keepdb True I want to reuse the user created in the previous test instead of creating a new one. With --reuse-db specified, I'm expecting the second test test_sign_in to detect the very same user. Instead, I get: >>> django_user_model.objects.count() 0 -
Show item, total price and total quantity in cart bag icon
Except my cart page, another page can't show item name, quantity and price on my web, this is my Project tree enter image description here base.html ` <div class="sinlge-bar shopping"> <a href="#" class="single-icon"><i class="ti-bag"></i> <span class="total-count">{{cart.get_total_product}}</span></a> <!-- Shopping Item --> <div class="shopping-item"> <div class="dropdown-cart-header"> <span>{{cart.get_total_product}} Items</span> <a href="{% url 'cart:cart_detail' %}">View Cart</a> </div> <ul class="shopping-list"> {% for item in cart %} {% with product=item.product %} <li> <a href="#" class="remove" title="Remove this item"><i class="fa fa-remove"></i></a> <a class="cart-img" href="{% url 'store:product' product.pk %}"><img src="{{product.image.url}}" alt="{{item.product.name}}" width="100" height="100"></a> <h4><a href="{% url 'store:product' product.pk %}">{{item.product.name}}</a></h4> <p class="quantity"> {{item.quantity}}x <span class="amount">{{item.price|floatformat:0|intcomma}}</span> </p> </li> {% endwith %} {% endfor %} </ul> <div class="bottom"> <div class="total"> <span>Total</span> <span class="total-amount">{{item.total_price|floatformat:0|intcomma}}</span> </div> <a href="{% url 'store:checkout' %}" class="btn animate">Checkout</a> </div> </div> </div> ` store/url.py ` app_name = 'store' urlpatterns = [ path ('',views.index, name='index'), path ('index.html',views.index, name='index'), path ('cart.html',views.cart_detail, name='cart'), path ('search.html',views.search_form, name='search'), path ('contact.html',views.contact, name='contact'), path ('checkout.html',views.checkout, name='checkout'),#/<int:pk>/ path ('blog-single-sidebar.html',views.blog, name='blog'), path ('shop-grid.html/<int:pk>/',views.shop, name='shop'), path ('product.html/<int:pk>/',views.product_detail, name='product'),#/<int:pk>/ path ('filter_by_prices.html',views.filter_by_prices,name='filter_by_prices') ] ` I try to add cart.py to use funtion with code like this but not working store/views.py from cart.cart import Cart def cart_detail(request): cart = Cart(request) return render(request, 'store:cart.html', {'cart': cart}) -
‘Fail due to unhealthy allocation' deploying django site using fly.io
I am super new to deployment and django and I’m trying to deploy a simple django site without database with fly.io. I’ve been getting errors for 4 days and would really appreciate it if anyone can help! The error is below ==> Creating release --> release v3 created --> You can detach the terminal anytime without stopping the deployment ==> Monitoring deployment Logs: https://fly.io/apps/chaplinhuang/monitoring 1 desired, 1 placed, 0 healthy, 1 unhealthy [restarts: 2] [health checks: 1 total] Failed Instances Failure #1 Instance ID PROCESS VERSION REGION DESIRED STATUS HEALTH CHECKS RESTARTS CREATED 00d71cce app 3 ord run pending 1 total 2 1m0s ago Recent Events TIMESTAMP TYPE MESSAGE 2022-12-26T02:05:54Z Received Task received by client 2022-12-26T02:05:54Z Task Setup Building Task Directory 2022-12-26T02:06:25Z Started Task started by client 2022-12-26T02:06:27Z Terminated Exit Code: 3 2022-12-26T02:06:27Z Restarting Task restarting in 1.042869453s 2022-12-26T02:06:44Z Started Task started by client 2022-12-26T02:06:46Z Terminated Exit Code: 3 2022-12-26T02:06:46Z Restarting Task restarting in 1.11932696s 2022-12-26T02:07:03Z [info][2022-12-26 02:07:03 +0000] [525] [INFO] Booting worker with pid: 525 2022-12-26T02:07:03Z [info][2022-12-26 02:07:03 +0000] [525] [ERROR] Exception in worker process 2022-12-26T02:07:03Z [info]Traceback (most recent call last): 2022-12-26T02:07:03Z [info] File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-12-26T02:07:03Z [info] worker.init_process() 2022-12-26T02:07:03Z [info] File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in … -
Django form validation
Is there an easier way to write validation for each item in a form? Maybe embed them in model declaration itself? class InfoUpdateForm(forms.ModelForm): class Meta: model = Profile fields = [ 'first_name', 'middle_name', 'last_name' ] def clean(self): cleaned_data = super().clean() first_name = cleaned_data.get('first_name') if not str(first_name).isalnum(): self._errors['first_name'] = self.error_class(['First name should constain only alpha numeric characters']) middle_name = cleaned_data.get('middle_name') if not str(middle_name).isalnum(): self._errors['middle_name'] = self.error_class(['Middle name should constain only alpha numeric characters']) last_name = cleaned_data.get('last_name') if not str(last_name).isalnum(): self._errors['last_name'] = self.error_class(['Last name should constain only alpha numeric characters']) -
Update Django model object field from shell
Model field displaying some zip codes as 4 characters only, ex: 1234 I want to change all zip codes with 4 characters to 5 by adding a "0" at the start, ex: 01234 Trying to find a way to do this from shell because I have a few thousand objects from app.models import Entry I tried: Entry.objects.filter(len(zip_code)==4).update("0"+zip_code) Entry.objects.filter(len(zip_code)==4).update(f("0"+{zip_code})) Error returned: Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'zip_code' is not defined -
Registration form not registering in users
I am doing the authentication of the users on my website but I have an issue with the form that doesn't take in users. Please help me Maybe I forgot something I am not that much experienced, thanks here is the form: class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter your password',})) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm password',})) class Meta: model = Account fields = ('first_name','last_name','phone_number', 'email', 'password') def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError( 'Passwords do not match' ) def __init__(self, *args, **kwargs): super (RegistrationForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs['placeholder'] = 'Enter your first name' self.fields['last_name'].widget.attrs['placeholder'] = 'Enter your last name' self.fields['phone_number'].widget.attrs['placeholder'] = 'Enter your phone number' self.fields['email'].widget.attrs['placeholder'] = 'Enter your email address' for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' model is here class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name,username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') user = self.model( email= self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name,username, email, password): user =self.create_user( #calling for create user method email=self.normalize_email(email), username=username, password=password, first_name=first_name, last_name=last_name, … -
Validation using django-crispy forms
Django has built in validators when using UserCreationForm which flags following error for example. How do I add similar inline validation with django-crispy forms? -
I can't make a foreign key filter
I have a model that has a key of itself, indicating whether it is a sub category or a larger category. class Categoria(TranslatableModel): translations = TranslatedFields( nome=models.CharField(max_length=255), icone=models.CharField(max_length=255, blank=True, null=True), ) categoria=models.ForeignKey( 'Categoria', on_delete=models.CASCADE, blank=True, null=True, related_name='categorias' ), def __str__(self): return 'Categoria {}'.format(self.nome) I would like to get the ones that don't have a category to indicate that they are parent categories but it generates this error: django.core.exceptions.FieldError: Cannot resolve keyword 'categoria' into field. Choices are: id, produtotranslation, translations I tried to use a common filter but it generates the error above categorias = Categoria.objects.filter(categoria__isnull=True)