Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
using django models to map one to many and many to one
I started using django today and am having trouble creating models based off the response of an API call. We can have a Course that gives a list of professors. Though, Professors can also teach multiple courses. I'm not sure how to create a list for both professors in the Course class and courses in the Professor class. Note: I am using MongoDB so I wasn't using the postgres ArrayFields. I have the following code: from django.db import models class Course(models.Model): department = models.CharField(max_length=4) course_number = models.CharField(max_length=4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) credits = models.IntegerField(max_length=1) gpa = models.DecimalField(max_digits=4, decimal_places=3) professors = ??? class Professor(models.Model): id = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=100, unique=True) reviews = models.BooleanField(default=True) courses = ??? I visited this stackoverflow post and wasn't sure if this was the best way to approach it considering this might be a bit outdated. I also viewed the ArrayFields class to attempt to use that but wasn't sure if that was only for postgres (because I'm using MongoDB) -
I don't have models.Model.objects
For some reason I can do almost everything on Django but access to model.objects, like, it doesn't even appear, I cannot delete nor find anything without that (or I do not know how), I'm learning django from a basic course. I use Python 3.11, Django 4.1.4, on Pycharm 2022.3. PD: If you know of another way of doing the Create, Read, Update and Delete of objects I would apreciate that. Sorry for the english. I tried searching on the web about this problem but sinsce I'm a noob on Django and trainee on python most things are like white noise to me, like, I don't understand. -
Ajax doesn't wait for server response
On this website I allow user to make some posts. The details of the posts are saved in the database and the file in the user account folder with Django file system. When I try to delete the post with Ajax I get the console.error from Ajax error: function(data). The ERROR. ERROR... Object { readyState: 0, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e) , … } delete_post.js:26:21 error http://127.0.0.1:8000/static/javascript/delete_post.js:26 jQuery 6 DeletePost http://127.0.0.1:8000/static/javascript/delete_post.js:7 DeleteP http://127.0.0.1:8000/UserProfile/alexandra28/:198 Here is the Html and JavaScript. <button class="delete" id="delete" type="button" name="button">Delete</button> <script> const post_id = {{post.post_id}} function DeleteP(post_pk){ const delete_btn = document.getElementById("delete") function onDelete(){ location.reload(true) } if (delete_btn != null){ delete_btn.addEventListener("click", function(){ DeletePost(post_id, onDelete(), delete_btn) }) } } //console.log(post_id) DeleteP(post_id) </script> Then Ajax. function DeletePost(post_id, uiUpdateFunction, delete_button){ //event.preventDefault() const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; payload = { "post_id": post_id, } $.ajax({ headers: {'X-CSRFToken': csrftoken}, type: 'POST', dataType: "json", url: "/delete_post_url/", //async: false, //cache: false, timeout: 0, data: payload, success: function(data){ console.log('SUCCESS: ' + data['response']) if(data['response'] == "Post deleted."){ delete_button.click() } else if(data['response'] != null){ alert("This is data: ", data['response']) } }, error: function(data){ console.error("ERROR...", data) alert(data.status); // the status code alert(data.responseJSON.error); // the message alert("Something … -
How do I get a value from a different model in django?
Im new to django and im trying to figure out how to set the value in a model = to a value in another model from django.db import models from django.contrib.auth.models import User class Company(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True, blank=True) # This is the value I want _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) companyName = # I want the name here _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name I've tried these but they dont work companyName = Company.name companyName = models.CharField(Company.name, max_length=100, null=True, blank=True) -
I would like to limit the borrowing objects in my Django app
I have an app that displays games and user can borrow them. I want to limit the amount of borrowed games for each user to max 3 games. I created two models borrow and games. The methods work well except for the max borrowing. # Method display borrowed games @login_required def borrows(request): borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed') context = {'borrows':borrows} return render(request, 'gameapp/borrows.html', context) ` # Methos allow the user borrow single game @login_required def borrow(request, boardgame_id): boardgame = Boardgame.objects.get(id=boardgame_id) if request.method != 'POST': form = BorrowForm() else: form = BorrowForm(data = request.POST) if form.is_valid(): borrow_boardgame = form.save(commit = False) borrow_boardgame.owner = request.user # Replace the borrow varibale from borrow Model to main game borrow_boardgame.borrow = boardgame form.save() return redirect('gameapp:borrows') context = {'boardgame': boardgame, 'form':form} return render(request, 'gameapp/borrow.html', context) ` ` # Method display borrowed games @login_required def borrows(request): borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed') context = {'borrows':borrows} return render(request, 'gameapp/borrows.html', context) # Methos allow the user borrow single game @login_required def borrow(request, boardgame_id): # I tried this boardgame = Boardgame.objects.get(id=boardgame_id) if request.method != 'POST': form = BorrowForm() else: form = BorrowForm(data = request.POST) if form.is_valid(): borrow_boardgame = form.save(commit = False) borrow_boardgame.owner = request.user # Replace the borrow varibale from borrow … -
How to handle search in a django app, when the search bar is located in a separate html file?
I programmed a website with Django. I have separated frequently repeated items, like navbar, in separate html files and I have used in them other pages using {%include%} tag. The search bar is also located in the navbar. When I try to handle search event, it does not work. Here is my search bar form: <form id="top-search-form" action="{%url 'search'%}" class="header-search-light" method="get"> <input type="search" name="search_query" class="search-input" placeholder="search..." required="" style="display: none;"> <button type="submit" class="search-button"> <i class="fa fa-search" aria-hidden="true"> </i> </button> </form> My search view is: def search(request): print('Hey, You are searching something!!') search_query = '' if request.GET.get('search_query'): search_query = request.GET.get('search_query') print("SEARCH: "+search_query) return HttpResponse(search_query) I'm not sure about what the solution is. I will appreciate your help guys. -
I cannot deploy my app to heroku after adding settings for static files
I am doing a project for college this was my first app with django I have no prior experience to this I am trying to deploy my app to heroku, I deployed it a couple of hours back with "DISABLE_COLLECTSTATIC" config and it was working. When I tried adding the static files settings the app was not working anymore, it still deploys but I get the "Application Error" when i open the app. This is settings.py import os from pathlib import Path import dj_database_url from django.contrib.messages import constants as messages import mimetypes development = os.environ.get('DEVELOPMENT', False) MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', '') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = development # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Default apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', 'bootstrap4', 'tinymce', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Does Python or Django have a built-in function that checks for a numbers value and returns a preset default if the value is None?
Does Python or Django have something like this built in? def f(value, if_None=0): if value is None: return if_None else: return value