Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
twitter:image meta tag problem in Django Blog
Twitter needs the hardcoded path in his metatags in order to render the image in the social media. I use the hardcoded path in my article_details.html, which is the main html for articles, but I need to switch to a new image path every time I publish new articles. I'm not using a single page for every article. Does any1 know a way to have a dynamic path for this metatag? -
Django TemplateDoesNotExist error in production but not in development
I am trying to release my website to a staging environment but I keep get TemplateDoesNotExist error. My website consists of multiple apps that will extend a base app for common elements. When I view the website in a development environment it works as expected, however when I try to view it in my staging environment it errors out. All of the templates in the apps, other than the base templates, contains {% extends "main/index.html "%} at the top of them. file structure: ├── manage.py ├── assets ├── base │ ├── templates │ │ ├── main │ │ │ ├── index.html │ ├── urls.py │ ├── views.py │ ├── ... ├── dashboard ├── inventory │ ├── templates │ │ ├── main │ │ │ ├── inventory.html │ ├── urls.py │ ├── views.py │ ├── ... ├── magic │ ├── templates │ │ ├── main │ │ │ ├── sets.html │ │ │ ├── cards.html │ ├── urls.py │ ├── views.py │ ├── ... ├── website │ ├── settings │ │ ├── base.py │ │ ├── staging.py │ │ └── production.py │ ├── asgi.py │ ├── urls.py │ └── wsgi.py settings/base.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent SECRET_KEY … -
Not able to install argon2 in windows 10
Argon2 lib is not getting installed in windows 10.Getting the following error. pip3 install argon2 Running setup.py install for argon2 ... error ERROR: Command errored out with exit status 1: package init file 'phc-winner-argon2_init_.py' not found (or not a regular file). I have installed Miscrosoft Visual Studio Build tools as well.And using Python 3.9.1 -
django query: grouped min and max that max is twice and newer of min
I need queryset that result contains rows from following model BuyerPower, that for each symbol contains maximum ibp and minimum ibp and ct columns of these two records, where maximum_ibp is more than twice minimum_ibp and newer. result table would look like this: | symbol(unique) | max_ibp | min_ibp | max_ibp_ct | min_ibp_ct | models: class BuyerPower(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) ct = models.DateTimeField(auto_now_add=True) ibp = models.FloatField() I've tried using values() and annotate() but I can not find how to filter and join max's that are newer of min min_ibps = IndividualBuyerPower.objects.filter().values('symbol', 'ct').annotate(min_ibp=Min('ibp')) max_ibps = IndividualBuyerPower.objects.filter().values('symbol', 'ct').annotate(max_ibp=Max('ibp')) -
Django forcing async database operation
raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. is thrown with following code if object_query.exists(): object_query is object_query = Example.objects.filter( name='test', ) -
Running celerybeat in production (Ubuntu)
I need to run celerybeat in production. Currently while development, I use to run while being in the directory i.e /Users/driftking9987/Documents/Django_Projects/inlog_p_v2 celery -A inlog_p_v2 worker -l info -B I have gone through the https://docs.celeryproject.org/en/stable/userguide/daemonizing.html link where it says how to run the celery beat as daemon onto the server. In the location, /etc/init.d , I have copied the sample init script from GitHub for celerybeat. As written in the documentation, I created a configuration file at location /etc/default whose contents are as follows: # Absolute or relative path to the 'celery' command: CELERY_BIN="/opt/anaconda/envs/django_env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="inlog_p_v2" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. CELERYBEAT_CHDIR="/opt/inlog_p_v2" # Extra arguments to celerybeat # CELERYBEAT_OPTS="--schedule=/var/run/celery/celerybeat-schedule" #export DJANGO_SETTINGS_MODULE="inlog_p_v2.settings" CELERYD_CHDIR="/opt/inlog_p_v2" Below is the error which I get when I try to run (base) root@ip-172-31-2-63:/etc/default# /etc/init.d/celerybeat start celery init v10.1. Using configuration: , /etc/default/celerybeat Starting celerybeat... Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for '-A' / '--app': Unable to load celery application. The module inlog_p_v2 was not found. I have been trying all the things which are written in so many threads over here, but nothing seems to … -
How to send value in session with forms in django
I have a favourite block, which is created using Session, I retrieved data from Session and displayed it in my template. In this favourite block I have a form that will send filled information to admin. I want to send with this form my received data from session, how to do that? This is my view: def favourites(request): fav = request.session.get('favourites') if not fav: return render(request, 'Main/favourites_empty.html', context={}) if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): # product = form.cleaned_data['product'] # print(product) form.save() return HttpResponseRedirect(reverse('index_urls')) else: form = RequestForm() commodities = Commodity.objects.filter(id__in=(x['id'] for x in fav )) context = { 'favourites': commodities, 'form': form } # for com in commodities: # print(com.id) # print(com.title) return render(request, 'Main/favourites.html', context) This is my template: <form method="post"> {% csrf_token %} <div class="form-item"> <!-- <input type="text" placeholder="Ваше имя"> --> {{ form.name }} </div> <div class="form-item"> <!-- <input type="text" value="{{form.phone}}" placeholder="Ваш телефон"> --> {{ form.phone }} </div> <div class="form-item"> <!-- <input type="text" value="{{form.email}}" placeholder="Ваш email"> --> {{ form.email }} </div> <div class="form-item"> <!-- <textarea placeholder="Комментарий"></textarea> --> {{ form.message }} </div> <button type="submit" class="bt">оставить заявку</button> </form> -
Can you correct the html pogo-slider code?
There seems to be some problems with the following code I downloaded from a free website template. Instead of showing my pictures, there is only white text on white background. I can only see the text if I mark it with the mouse. Is there something wrong with the code? <!-- Start Banner --> <div class="ulockd-home-slider"> <div class="container-fluid"> <div class="row"> <div class="pogoSlider" id="js-main-slider"> <div class="pogoSlider-slide" style="background-image:url(images/sladd_ur.jpg);"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="slide_text white_fonts"> <h3>Progress & Success<br><strong>Currency</strong></h3> <br> <a class="start_exchange_bt" href="exchange.html">Start Exchange ></a> </div> </div> </div> </div> </div> <div class="pogoSlider-slide" style="background-image:url(images/sladd_i.jpg);"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="slide_text white_fonts"> <h3>Progress & Success<br><strong>Currency</strong></h3> <br> <a class="start_exchange_bt" href="exchange.html">Start Exchange ></a> </div> </div> </div> </div> </div> </div> <!-- .pogoSlider --> </div> </div> </div> <!-- End Banner --> -
Does Django's models.TextField() provide much security when not used with Django's form validation?
I have a Django App that accepts user input in a free text field. In the model I have the following validation rule for the field: body = models.TextField(blank=True, null=True) If I decide not to validate input in the front end and I don't use Django forms, am I leaving a big gaping security hole, or does models.TextField() provide quite a lot of protection? For context, I'm sending data via AJAX and in this case I think it would be easier to not use a Django Form, that's very possibly because I don't know Django well enough, but I think the question still stands. -
How do i write a function to list replies and a option to create replies in comments details page Django RestFramework
I want to add a function to to show all the replies of a Parent Comment and option to add new replies to parent comments in Django RestFramework. How do i approach? Here's my code: Models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='Comments') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='Replies') conversation = models.TextField() created_on = models.DateTimeField(default=timezone.now) approved_comments = models.BooleanField(default=False) def __str__(self): return self.article.title[:50] + ' | ' + 'Comments by {}' .format(self.user.username) def approved_comments(self): self.approved_comments = True self.save() def children(self): # Return replies of a comment. return Comment.objects.filter(parent=self) @property def is_parent(self): # Return `True` if instance is a parent if self.parent is not None: return False return True Serializers.py class CommentDetailSerializer(ModelSerializer): url_to_commentUpdate = comment_update_url url_to_commentDelete = comment_delete_url user = SerializerMethodField() class Meta: model = Comment fields = ['id', 'article', 'conversation', 'created_on', 'user', 'url_to_commentUpdate', 'url_to_commentDelete' ] def get_user(self, obj): return str(obj.user.username) # Need To Display replies in Comments Detail Page # Need To add function to add new replies class CommentCreateUpdateSerializer(ModelSerializer): class Meta: model = Comment fields = ['article', 'conversation'] Views.py class CommentDetailAPIView(RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentDetailSerializer permission_classes = [AllowAny] -
Is it okay to copy a class method and test its behavior by mocking the class and dependencies in unit tests?
Or I need mock all other methods and dependencies(huge amount) in the class by using @patch, and test through a class call(call method cls.execute() in my service)? I'm new to testing. So copying the method and testing it separately, checking the desired changes in the mocked class seems like a good idea to me. But is it really so? -
How to protect Malicious attack on django website
My company's site is hosted on AWS. I have 3 months experience so I don't know what is: Not Found: //admin/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //api/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //backup/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //beta/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //blog/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //cms/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //demo/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //dev/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //laravel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php The problem is the server automatically stopped running. I thought possible reason can be that the code is going inside some loop so I decided to check logs. What I found is: Not Found: //admin/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //api/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //backup/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //beta/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //blog/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //cms/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //demo/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //dev/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //laravel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/phpunit/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //lib/phpunit/src/Util/PHP/eval-stdin.php Not Found: //new/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //old/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //panel/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php Not Found: //phpunit/Util/PHP/eval-stdin.php I don't know what is this and how to deal with it. I already searched on google I found that it is some kind of malicious attack, I am not sure. I want to know what is this. The site is Django web framework. -
Subtract time in django Models.py
I tried subtracting two times in models.py but I got error. Here is my model That I have been working. class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) travel_date_time = models.DateTimeField() and BusCompanyRoute have journey length. class BusCompanyRoute(BaseModel): journey_length = models.TimeField(null=True) Now I tried subtracting these times in using @property decorator in following way @property def journey_end_time(self): return self.travel_date_time.time()+self.bus_company_route.journey_length but end up getting following error warning as: Class 'time' does not define '__add__', so the '+' operator cannot be used on its instances How can I solve it? -
Why is the rating selected in the form not inster to the database?
So this is my code: models.py: class Company(models.Model): class Meta: verbose_name_plural = 'Companies' COMPANY_STATUS_CHOICES = ( ('Active', 'Active'), ('Dissolved', 'Dissolved'), ) COMPANY_SIZE_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large'), ) company_name = models.CharField(max_length=150, null=True) company_number = models.CharField(max_length=15, null=True) company_vat_number = models.CharField(max_length=20, null=True) company_status = models.CharField(choices=COMPANY_STATUS_CHOICES, max_length=20, default='Active', null=True) company_size = models.CharField(choices=COMPANY_SIZE_CHOICES, max_length=20, default='Small', null=True) company_rating = models.ForeignKey(Company_rating, on_delete=models.SET_NULL, null=True) def __str__(self): return self.company_name views.py: def suppliers_create(request): form = SuppliersForm() if request.method == 'POST': form = SuppliersForm(request.POST) if form.is_valid(): company_name = form.cleaned_data['company_name'] company_number = form.cleaned_data['company_number'] company_vat_number = form.cleaned_data['company_vat_number'] company_status = form.cleaned_data['company_status'] company_size = form.cleaned_data['company_size'] company_rating = form.cleaned_data['company_rating'] Company.objects.create( company_name=company_name, company_number=company_number, company_vat_number=company_vat_number, company_status=company_status, company_size=company_size, company_rating=company_rating, ) return redirect('/suppliers') context = { 'form': SuppliersForm() } return render(request, 'suppliers/suppliers_create.html', context) forms.py: class SuppliersForm(forms.Form): COMPANY_STATUS_CHOICES = ( ('Active', 'Active'), ('Dissolved', 'Dissolved'), ) COMPANY_SIZE_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large'), ) COMPANY_RATING_CHOICES = ( ('Perfect', 'Perfect'), ('Average', 'Average'), ('Bad', 'Bad'), ) company_name = forms.CharField() company_number = forms.CharField() company_vat_number = forms.CharField() company_status = forms.ChoiceField(choices=COMPANY_STATUS_CHOICES, label='Company Status') company_size = forms.ChoiceField(choices=COMPANY_SIZE_CHOICES, label='Company Size') company_rating = forms.ChoiceField(choices=COMPANY_RATING_CHOICES, label='Company Rating') The company_rating field on the form is displayed, but unfortunately what I selected is not inserted into the database, I don't see what I chose on admin. I … -
All my rows are still visible eventhough i am filtering
THis my first time using the django filter and i am trying to filter my all my records are still show even do my url says it is filtering the my records- any help will be appreciated This my filter File class Clientsearch(django_filters.FilterSet): class Meta: model = client fields ='__all__' exclude = ['Companyemail','Telephone','address','Postcode','RegNom','UTRno','PAYE','VAT','pensionusername','pensionpassword','companyfilling','authenticationcode','gatewayonlineuserid','gatewayonlinepassword', 'finacialdate', 'confirmationdate', 'agreedfees','updated_at','created_at','datejoined'] This my view.py def manage_client(request): clients=client.objects.all() myFilter = Clientsearch(request.GET,queryset = clients) context = {'myFilter':myFilter,'clients':clients} clients = myFilter.qs return render(request,"admintemplate/manage_client_template.html",context) This the Html Code for my Table - All the rows are still show but i can see in the url it is filtering <br> <div class="row"> <div class="col"> <div class="card card-body"> <form method ="get"> {{myFilter.form}} <button class="btn btn-primary" type ="submit">Search</button> </form> </div> </div> </div> <br> <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>ID</th> <th>Company Name</th> <th>Company Email</th> <th>Sector</th> <th>Employee Assigned</th> <th>Edit</th> <th>Delete</th> </tr> {% for client in clients %} <tr> <td>{{client.id}}</td> <td>{{client.Companyname}}</td> <td>{{client.Companyemail}}</td> <td>{{client.sector}}</td> <td>{{client.username}}</td> <td><a href="/edit_client/{{ client.id}}" class ="btn btn-success">Edit</a></td> <td><a href="/delete_client/{{ client.id}}" class ="btn btn-success">delete</a></td> {% endfor %} </table> </div> </div> </div> -
update onetoone using django CreateView
I am using CreateView to update my Person model. That model has a onetoone relation with Adress. When trying to update my Person model I cannot update the Adress model at the same time. It just gives me a list of existing addresses, but no way to add an new address. I can see that this is possible in admin. is it possible to this in th CreateView? model.py: class Person(Model): fname=CharField(default="missing",max_length=100) lname=CharField(default="missing",max_length=100) mobil=PhoneField(default='9999999999') mail=EmailField(default='contact@gmail.com') padress=OneToOneField(Adress,on_delete=CASCADE,primary_key=True) def __str__(self): return self.fname class Meta: ordering=('fname','lname') class Adress(Model): street=CharField(default='missing',max_length=100) snumb=CharField(default='missing',max_length=15) town=CharField(default='missing',max_length=100) postn=CharField(default='99999',max_length=5,validators=[postnvali]) def __str__(self): return self.town class Meta: ordering=('street','town') view.py class PCreate(CreateView): template_name='kammem/create.html' model=Person fields=['fname','lname','mobil','mail','padress'] success_url=reverse_lazy('forl') url.py path('pcreate/',PCreate.as_view(),name='pcreate'), template: {% extends 'edit2.html' %} {% block add %} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} any suggestions? -
How to allow http djnaog heroku
I tried this MIDDLEWARE = [ # SecurityMiddleware must be listed before other middleware 'django.middleware.security.SecurityMiddleware', # ... ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True but still didn't change anything I tried this package [django-sslify][1] and added its middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'sslify.middleware.SSLifyMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', but it gives me this error TypeError: SSLifyMiddleware() takes no arguments error traceback: System check identified 2 issues (0 silenced). January 31, 2021 - 09:14:56 Django version 3.1.5, using settings 'dashboard.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/hazem/.local/share/virtualenvs/dashboard-tUiBEpKo/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in … -
Django- distinct doesn't work on order by
I have 2 models as follows: class Chat(models.Model): name = models.CharField(max_length=20) class ChatMessage(models.Model): chat = models.ForeingKey(Chat, related_name="messages") text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to get all chats order by last message created datetime. Some chats may not have messages, so I want to be at the end of the list. I tested following ways: 1- chats = Chat.objects.all().order_by(F('messages__created').desc(nulls_last=True)).distinct() 2- chats = Chat.objects.all().order_by('-messages__created').distinct() 3- chats = Chat.objects.all().annotate(last_message=Max("messages__created").order_by("-last_message") ways 1 and 2 return duplicate values. way 3 return non-duplicate date but chats with no message are on the top of the list. I want to be at the end of the list. -
Django search returns an empty value
def book(request): books = Library.objects.all() form = ChoiceFilterForm(data=request.GET or None) if form.is_valid(): filter_choice = form.cleaned_data['filter_choice'] books = books.filter(category=filter_choice) if filter_choice == 'null': books = Library.objects.all() query = request.GET.get('search') if query and query != '': result = Library.objects.filter(Q(title__icontains=query)).distinct() else: result = Library.objects.all() context = {'books': books, 'form': form, 'result': result, 'query': query} return render(request, 'book.html', context) I am new to django and I want to make a search bar. Program doesn't return an error message but the search bar shows nothing. What is my mistake here? -
how to implement CI/CD for Django project on AWS Lightsail from Bitbucket
I am trying to implement a Bitbucket CI/CD pipeline to deploy my Django project which is already deployed on AWS lightsail. after two hours of searching, I found a lot of information but none of them are exactly like my case. I have a few questions: 1- how to write a .yml file for my project that is already deployed on lightsail? 2- how to choose between codedeploy, jenkins, and other proposed tools for deploying and testing? 3- lots of articles are talking about EC2 but I'm using lightsail, is there the same configuration? a doc or tutorial for writing docker file for django project and yml file would be perfect. -
TypeError: 'NoneType' object is not iterable While Decleare Context Processor in Django Project
I want to pass a context value without rendering a page, that's why I implemented context processor. But when I return a context value from that function it showing me this error. here is my code for payment.py: def payment_url(request): todays_date = date.today() now = datetime.datetime.now() mcnt_TxnNo = "Txn" + str(todays_date.year) + str('{:02d}'.format( todays_date.month)) + str(todays_date.day) + str(now.hour) + str(now.minute) + str('{:02d}'.format(now.second)) order_no = "ON" + str(todays_date.year) + str('{:02d}'.format( todays_date.month)) + str(todays_date.day) + str(now.hour) + str(now.minute) + str('{:02d}'.format(now.second)) secret_key = b"***" print(mcnt_TxnNo) if request.method == 'POST': name = request.POST["clientName"] phone = request.POST["phone"] address = request.POST["address"] email = request.POST["clientEmail"] product_name = request.POST["proName"] print("product Name", product_name) paid = request.POST["paid"] print(name) string = "***" print(string) byte_string = bytes(string, 'utf-8') hash_code = hmac.new(secret_key.upper(), byte_string, hashlib.sha256) hash_text = hash_code.hexdigest() print(hash_text) jsonObj = { // json object } json_string = json.dumps(jsonObj) print(json_string) url = "**" headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) return {'payment_link': payment_link} else: return {} And my setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Cripsy forms prepend is not showing up anywhere in the DOM
I am using this forms.py file and I want to prepend an icon to my field with Django Crispy Forms, but when I run this nothing appears on the screen. I have done everything that I could and nothing I research is helping. It is not even appearing anywhere in the DOM. In my html template inside a form element I am doing {{ form|materializecss }} and I have brought in the crispy forms tags {% load crispy_forms_tags %} {% crispy UpdateProfileForm %} as well. Whats wrong with this code? Why isn't it putting an icon before my profile_picture file input field? from crispy_forms.bootstrap import PrependedText from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout from django import forms from django.forms.models import ModelForm from django.forms.widgets import TextInput class UpdateProfileForm(ModelForm): class Meta: model = UserInformation fields = [ 'profile_picture', ] def __init__(self, *args, **kwargs): super(UpdateProfileForm, self).__init__(*args, **kwargs) # this is for crispy forms self.helper = FormHelper() self.helper.layout = Layout( PrependedText('profile_picture', '<i class="material-icons">photo</i>'), ) -
Django - how to combine multiple filter parameters together, where the number of parameters is variable
I'm trying to implement a search function on Django. If my query is: "a b c", then I want to to search : select * from table where col LIKE '%a%' and col LIKE '%b%' and col LIKE '%c%' I see I can do that with table.objects.filter(col__icontains('a')) But how do I make this work for a,b & c. I can't hard-code the number of parameters. There might be a,b,c,d or any number of search terms.? -
How to create Django database custom user fields creation problem. Use User.objects.create_user()
I create a custom user information field on django. But on admin database hobby and bio field not create. myuser = User.objects.create_user(username, email,password) myuser.hobby = friendid myuser.first_name = "sami" myuser.last_name = "khan" myuser.bio = "khanann" myuser.save() And my model.py class User(AbstractUser): hobby = models.CharField(max_length=113) bio = models.TextField() admin.py @admin.register(User) class CoreAdmin(admin.ModelAdmin): list_display = ("id", "first_name", "last_name") i also make migrate my database. -
Rest API Requests drop on Django framework
There are some web services developed in python and Django framework in Windows server Also, Waitress serves Django In addition, Nginx has chosen as a web server, but Django is not served on Nginx there are some problems when users are more than 80 per seconds First of all: Requests not queued and receive sadly and periodic (It seems they are buffering) Second: Many requests dropped Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it