Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make images show using apache2 for django website deployed on digital ocean? [closed]
Please assist How to make images show using apache2 for django website deployed on digital ocean ? -
How to use TailwindCSS with Django?
How to use all features of TailwindCSS in a Django project (not only the CDN), including a clean workflow with auto-reloading, and purgeCSS step to be production-ready? When googling, I found a npm package named django-tailwind but it did not really helped me in the process. -
'NoneType' object has no attribute in Django?
I am creating a function in models, and its giving me this error 'NoneType' object has no attribute 'price', please check my code and please let me know where i am mistaking. i have the relation between product and orderitem table here is my models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) totalprice=models.IntegerField() price = models.IntegerField() def __str__(self): return self.name class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total here is my list.html file... {% for item in items %} <div class="media-body"> <a href="javascript:void()"> <h4>{{item.product.name}}</h4> </a> <h4><span>{{item.quantity}}</span></h4> <h4><span>$ {{item.get_total}}</span></h4> </div> {% endfor %} -
Django Model object creation method
I'm having two models where UserGroup model, which contains a group admin, and DetailedUser model which related to the group model, where the field user points all users in the certain UserGroup, I want to add a field that when a new user added to the group it store its date and time of user added to the particular group. class UserGroup(models.Model): group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_by') group_name = models.CharField(max_length=100) group_amount = models.PositiveSmallIntegerField() def __str__(self): return self.group_name class DetailedUser(models.Model): group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name='user_group') user = models.ManyToManyField( User, related_name='single_user') user_added = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return f"{self.group.group_name}" How can I done this method? -
For Implementing Elastic Search in Django Which Library is the best?
I need to implement a Elastic search in my project .... SO when I go through some research I can found that multiple libraries are available . 1 ) elasticsearch-django 7.0 https://pypi.org/project/elasticsearch-django/ 2 ) django-elasticsearch-dsl 7.1.4 https://pypi.org/project/django-elasticsearch-dsl/ 3 ) HAystack https://django-haystack.readthedocs.io/en/master/ Anyone help me to found the best one .... THanks in Advance -
Django: How to send data from forum page to message page?
I am trying to receive data from textarea in the forum.html and display on the message.html page. here is forum.html: <div class="forum_input"> <form action="forum" method="post"> {% csrf_token %} <textarea name="post" id="" cols="30" rows="10"></textarea> <br> <button type="button" class="btn btn-info">Poser</button> </form> </div> And here is the method in views.py that treats data from forum.html @login_required(login_url='login') def forum(request): if request.method == 'POST': post = request.POST['post'] if post.is_valid(): post = post.cleaned_data['post'] post.save() return render(request, 'forum.html', {'post': post}) return render(request, 'forum.html') Now the question is, what to write on the method messages in views.py that renders messages.html, in order to get displayed the content of the forum.html which is rendered by forum.py in the views.py. Ps: messages.html is just empty html file for the moment. -
Incorrect data being sent to views.py from javascript in a django website
I am working on a basic django ecom. website. I have come across a problem which I am not able to solve. The problem is that on the products page of my website every product has a select box for size of the item and every select box has the same id (As i am iterating over the products). So whenever I choose a size for any product other than the first product the size selected from the first select box under first product goes to my database instead of the size selected under that product. This is my html: {% if product.id in list_cart %} <div class="btn-group" style="display: none;"> <select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> </div> {% else %} <div class="btn-group"> <select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> </div> {% endif %} And this is my javascript: var updateBtns = document.getElementsByClassName('update-cart') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action var sizebox = document.getElementById("sizebox"); var size = sizebox.options[sizebox.selectedIndex].value; console.log(size) updateUserOrder(productId, action, size) }) } I want to figure out a … -
Docker + Django Disallowed hosts
When I run python manage.py runserver without docker - it work But when I run docker-compose up - it raise this error Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. my ALLOWED_HOSTS: ALLOWED_HOSTS = ['*', '0.0.0.0', 'localhost'] docker-compose.yml: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/TestTask ports: - "8000:8000" depends_on: - db if you need more info - leave comment, and I update the question -
Python version control on package
i have problem on python control version of my package error: Because django-cors-headers (3.4.0) requires Python >=3.5 and no versions of django-cors-headers match >3.4.0,<4.0.0, django-cors-headers is forbidden. So, because dashboard depends on django-cors-headers (^3.4.0), version solving failed. ERROR: Service 'webapp' failed to build: The command '/bin/sh -c poetry install --no-root --no-dev' returned a non-zero code: 1 package [tool.poetry.dependencies] python = "^3.8" asgiref = "^3.2.10" autopep8 = "^1.5.3" django = "^3.0.7" pycodestyle = "^2.6.0" pytz = "^2020.1" sqlparse = "^0.3.1" Unipath = "^1.1" dj-database-url = "^0.5.0" gunicorn = "^20.0.4" whitenoise = "^5.1.0" django-rest-framework = "^0.1.0" pillow = "^7.1.2" django-pdb = "^0.6.2" django-cors-headers = "^3.4.0" django-environ = "^0.4.5" psycopg2 = "^2.8.5 if i put python = ">=3.5", it remove the error but add a new one with django with the same error require >=3.6. so how do this control version works like ? i am kind confuse. -
I am trying to integrate a payment gateway with paytm but it is not redirecting to payment page of paytm
def initiate_payment(request): if request.method == "GET": return render(request, 'user_login/pay.html') try: username = request.POST['username'] password = request.POST['password'] amount = int(request.POST['amount']) user = authenticate(request, username=username, password=password) if user is None: raise ValueError auth_login(request=request, user=user) except: return render(request, 'user_login/pay.html', context={'error': 'Wrong Accound Details or amount'}) transaction = Transaction.objects.create(made_by=user, amount=amount) transaction.save() subscription = Subscription.objects.update(subscribe='subscribed') subscription.save() merchant_key = settings.PAYTM_SECRET_KEY params = ( ('MID', settings.PAYTM_MERCHANT_ID), ('ORDER_ID', str(transaction.order_id)), ('CUST_ID', str(transaction.made_by.email)), ('TXN_AMOUNT', str(transaction.amount)), ('CHANNEL_ID', settings.PAYTM_CHANNEL_ID), ('WEBSITE', settings.PAYTM_WEBSITE), # ('EMAIL', request.user.email), # ('MOBILE_N0', '9911223388'), ('INDUSTRY_TYPE_ID', settings.PAYTM_INDUSTRY_TYPE_ID), ('CALLBACK_URL', 'http://127.0.0.1:8000/callback/'), # ('PAYMENT_MODE_ONLY', 'NO'), ) paytm_params = dict(params) checksum = generate_checksum(paytm_params, merchant_key) transaction.checksum = checksum transaction.save() paytm_params['CHECKSUMHASH'] = checksum print('SENT: ', checksum) return render(request, 'user_login/redirect.html', context=paytm_params) -
Is django's bulk_create atomic?
Will Django rolls back changes if there is any failure while batch creation of objects using bulk_create() in django? Or should I explicitly use transaction.atomic()? I have Foreignkey references in my models which might not be present in database. I'm using Django 1.11 -
Django prevent from saving model object on overriding save()
class Team(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="host") guest = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="guest") def save(self, *args, **kwargs): if self.host == self.guest: # want to prohibit saving object super().save(*args, **kwargs) I want to prohibit saving object if host and guest is the same. How to do this? I don't want to call super().save(*args, **kwargs) -
queryset.get(pk=value) throws a MultipleObjectsReturned exception
I am getting a weird issue in Django. I cannot debug the issue, because the issue is reported by a client test only through a bug tracker. A MultipleObjectsReturned exception is thrown in some cases when the queryset.get(pk=value) statement is called. The pk is the primary key in the table and it doesn't have duplicated values. It is a really strange issue and I cannot find possible causes of this issue. Is there anyone who faced this strange issue and fixed it? -
heroku django deployment error Application log
check Application log I had deployed my Django project on Heroku , I had tried many times but what exactly problem is , i am unable to get , please help me -
Django 2.0 issues with Migration auth.0009_alter_user_last_name_max_length
I am busy upgrading from Django 1.11 to 2.0 and I have come across the below error. I don't understand what rule _RETURN is, I am assuming the problem is not on Django's side, but I don't know where to look for the problem. Is anyone able to point me in the right direction? Operations to perform: Apply all migrations: admin, auth, cms, contenttypes,, menus, referrals, sessions, sites, social_django, taggit Running migrations: Applying auth.0009_alter_user_last_name_max_length...Traceback (most recent call last): File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.NotSupportedError: cannot alter type of a column used by a view or rule DETAIL: rule _RETURN on view progression depends on column "last_name" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/user/venvs/projenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line … -
how to iterate array of dictionary without loop using django?
This my scenario. I have 30 records in the array of dictionary in django. So, I tried to iterate it's working fine. but it takes around one minute. How to reduce iteration time. I tried map function but it's not working. How to fix this and I will share my example code. Example Code def find_places(): data = [{'a':1},{'a':2},{'a':3},{'a':4},{'a':5},{'a':6},{'a':7},{'a':8}] places =[] for p in range(1,len(data)): a = p.a try: s1 = sample.object.filter(a=a) except: s1 = sample(a=a) s1.save() plac={id:s1.id, a:s1.a} places.append(plac) return places find_places() I need an efficient way to iterate the array of objects in python without a loop. -
Django ORM remove unwanted Group by when using Count
I want to create a query something like this in django ORM. SELECT COUNT(CASE WHEN myCondition THEN 1 ELSE NULL end) as numyear FROM myTable Following is the djang ORM query i have written year_case = Case(When(added_on__year = today.year, then=1), output_field=IntegerField()) qs = (ProfaneContent.objects .annotate(numyear=Count(year_case)) .values('numyear')) This is the query which is generated by django orm. SELECT COUNT(CASE WHEN "analyzer_profanecontent"."added_on" BETWEEN 2020-01-01 00:00:00+00:00 AND 2020-12-31 23:59:59.999999+00:00 THEN 1 ELSE NULL END) AS "numyear" FROM "analyzer_profanecontent" GROUP BY "analyzer_profanecontent"."id" All other things are good, but django places a GROUP BY at the end leading to multiple rows and incorrect answer. I don't want that at all. Right now there is just one column but i will place more such columns. -
Ajax in django: JsonResponse returns nothing
I am trying to call a django view using ajax to retrieve data from the server. projectCreation is executed and render the template ProJectCreate.html for user input. In this Template a button with an id btnSelect will trigger the call for the ajax getFeatures.js. the Ajax supposedly returen the features but nothing was returned. The JsonResponse data should be displayed in the TextArea with an id id_features. URL: path('project/<int:pk>/', projectCreation, name='create-project') THE TEMPLATE: ProJectCreate.html {% extends "base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content %} **<p id="baseID" hidden="true">{{ base.id }} </p>** <div class="card border-left-info mb-1 shadow"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class='form-group'> {{ form.name|as_crispy_field }} </fieldset> <fieldset class='form-group'> {{ form.description|as_crispy_field }} </fieldset> <fieldset> {{ form.features|as_crispy_field }} **<a id="btnSelect" class="btn btn-outline-success mt-3 mb-4 pull-right" href="#">Get Columns</a>** </fieldset> <button class="btn btn-outline-success" type="submit">Submit</button> </form> </div> {% endblock content %} {% block javascripts %} <script src="{% static "js/getFeatures.js" %}"></script> {% endblock javascripts %} CREATE PROJECT VIEW: def projectCreation(request, **kwargs): pk = kwargs.get('pk') base = Base.objects.get(id=pk) context = {} context['base'] = base if request.method == 'POST': form = ProjectCreateForm(pk, request.POST) name = request.POST.get(u'name') description = request.POST.get(u'description') features = request.POST.get(u'features') if form.is_valid(): formProj = form.save(commit=False) try: formProj.name = name … -
Django rest framework custom permissions not working
i have implemented django restframework custom permissions class for staff-user . but in my case permission_class is not working. It would be great if any could figure out where i made mistake. permissions.py : from rest_framework import permissions class IsStaff(permissions.BasePermission): def has_object_permission(self, request, obj): return obj.owner == request.user.is_stff() views.py : from .permissions import (IsStaff) class CuboidListApiView(generics.ListAPIView): model = Cuboid queryset = Cuboid.objects.all() serializer_class = CuboidSerializer permission_classes = [IsStaff] -
Should the storage for my website be located closer to the host server or the client server?
My website is hosted on a US based server, but my target audience is in India. I just want to display some images from the storage (Amazon S3) what location should I choose for my storage? India or Amazon? -
'latin-1' codec can't encode characters in position 51732-51735: ordinal not in range(256) Django
i have problem with this error 'latin-1' codec can't encode characters in position 51732-51735: ordinal not in range(256) how can i solve that problem? this is my views.py code def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = io.StringIO() pdf = pisa.pisaDocument(io.StringIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) def myview(request, pk): postingan_list = Pengajuan_SKTM.objects.filter(id=pk) return render_to_pdf( 'pengurusan/pdf_template.html', { 'pagesize':'A4', 'postingan_list' : postingan_list, }) and this is my urls.py code url(r'^(?P<pk>[0-9]+)/myview/$', views.myview, name='print') -
Django-messages works only when form|crispy is used but not in other cases
I am creating a login page using django but it does not show any messages when I enter wrong passwords or email addresses. I've also checked other messages but it didn't help. login.html <div class="right"> <h2>Login</h2> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <div class="field"> <div class="label">Email or Username</div> <input type="text" name="username" id="username" class="form-control"> </div> <div class="field"> <div class="label">Password</div> <input type="password" name="password" id="password" class="form-control"> </div> <button class="login" type="submit">LOGIN</button> </fieldset> </form> <div class="sign_up"> <small>Don’t have an account yet?</small> <a class="signup" href="{% url 'register' %}">SIGN UP</a> </div> </div> urls.py has this path for the login page(I have imported all the necessary classes): path('login/', auth_views.LoginView.as_view(template_name='users/login.html') , name='login'), But the messages are shown when I use this form|crispy in login.html <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Login</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign In</button> </div> </form> <div class="border-top pt-3"> <small class="muted-text"> Want a new Account? <a class="ml-1" href="{% url 'register' %}">Sign Up</a> </small> </div> </div> -
How to convert a div css line to django template line for this particular line?
I want to convert a particular template line containing and inline css into django template line which will show the static files too. The template line is <div class="single-welcome-slides bg-img bg-overlay jarallax" style="background-image: url(img/bg-img/1.jpg);"> What will be the django static template line to load the image? -
Where is the pelican function section is in pelican documentation?
Where is Function information present in documenation? articles_page.previous_page_number() This function I don't know where is written. From where it get imported and used. -
How to send image to one chat and return automatically the image in whatsapp sticker?
i've been reading and i think the only way to create stickers is with third party apps. But, can i create a whatsapp number using Twilio or another and send an image message and automatically receive the image but in sticker? I'm beginning in the programming world and i would like to do that. I could use javascript(Nodejs) or python(Django)..