Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autlib vs OAuthlib: Are these libraries the same?
I am a beginner in the world of the OAuth2.0 and OpenID Protocols. I would like to implement a custom server - provider for multiple applications. So, to use it for Single Sign-On (SSO). I would like to work with python. Till now I have found four packages, for an OAuth2.0 and an OpenID Connect server implementation, in Python: pyoidc, django-oidc-provider, Django OAuth Toolkit (DOT) by OAuthlib and Authlib. I tried to read and understand pyoidc, but it was not so helpful and easy, basic things were missing. I have tried django-oidc-provider and I was really satisfied, and the whole implementation was really easy. So, after those trials, I am left with Django OAuth Toolkit (by OAuthlib) and Authlib. Has anyone tried them? Are these packages the same? Is Authlib an updated version of the OAuthlib library? The only information I know till now, is that Flask-OAuthlib is deprecated, and Authlib is was its new version. *Every answer or advice or personal experience would be really helpful and always appreciated! Thank you again for your help. -
i cant make the image_url to load on local host please hlp
i am making like a demo website that sells fruits i am following a youtube tutorial by (code with mosh) his images loaded properly but my images wont other things like add to cart button and name of product loaded properly. i ghave added on one url i.e ( https://upload.wikimedia.org/wikipedia/commons/7/7b/Orange-Whole-%26-Split.jpg ) admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Product, ProductAdmin) admin.site.register(Offer, OfferAdmin) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('New products') index.py {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ image_url }}" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ … -
Can we create a Rest API view using DRF to download a file from server?if yes please share a code snippet
I am trying a way to download log file from server without sharing ssh credentials to all the developers,please help me . I have tried looking for its solutions,and did not get one. -
Django count sub-objects with ntext on SQL Server
I have a Claim object with ClaimAttachment with a simple foreign key. I want to filter Claims that have more than x attachments. Normally, I would just do: Claim.objects.annotate(att_count=Count("attachments")).filter(att_count__gt=5) Easy. Except that Claim has several ntext fields and that results in: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. (306) (SQLExecDirectW)') That is because Django is making an outer join between Claim and ClaimAttachment and is grouping on all fields from Claim. Several of those fields being ntext, they can't be grouped by. I tried to work around the issue by doing a subquery myself: att = ClaimAttachment.objects.filter(claim_id=OuterRef("id")).aggregate(count=Count("id")) Claim.objects.annotate(att_count=Subquery(att)).filter(att_count__gt=5) But the aggregate cannot be done on the OutRef query. I can move the Count to the annotate(att_count=Count(Subquery(att))) but I'm back to square one because it's trying to group by all fields again. I know that this is not really Django's fault but rather another SQL Server annoyance but I don't control this data model, let alone the database server setup. How can I work around this limitation and get my attachment count ? -
Custom bool icons for Django Admin
I have a bool column in DjangoAdmin which shows the red and green icons like so: The client it's for however is requesting blue and yellow icons since it's what they've been using for years. Is there any way to replace these and use my own custom icons? -
'RuntimeError: populate() isn't reentrant'
I am seeing the following in my logs and my site isn't loading when I visit it. Can anyone tell me how I can fix this? Target WSGI script '/svr/myproject/myproject/wsgi.py' cannot be loaded as Python module. RuntimeError: populate() isn't reentrant [Mon Mar 30 00:09:55.290149 2020] [wsgi:error] [pid 19620] [...] mod_wsgi (pid=19620): Target WSGI script '/svr/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Mon Mar 30 00:09:55.290192 2020] [wsgi:error] [pid 19620] [...] mod_wsgi (pid=19620): Exception occurred processing WSGI script '/svr/myproject/myproject/wsgi.py'. [Mon Mar 30 00:09:55.290211 2020] [wsgi:error] [pid 19620] [...] Traceback (most recent call last): [Mon Mar 30 00:09:55.290231 2020] [wsgi:error] [pid 19620] [...] File "/svr/myproject/myproject/wsgi.py", line 16, in <module> [Mon Mar 30 00:09:55.290270 2020] [wsgi:error] [pid 19620] [...] application = get_wsgi_application() [Mon Mar 30 00:09:55.290279 2020] [wsgi:error] [pid 19620] [...] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Mon Mar 30 00:09:55.290294 2020] [wsgi:error] [pid 19620] [...] django.setup(set_prefix=False) [Mon Mar 30 00:09:55.290302 2020] [wsgi:error] [pid 19620] [...] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup [Mon Mar 30 00:09:55.290313 2020] [wsgi:error] [pid 19620] [...] apps.populate(settings.INSTALLED_APPS) [Mon Mar 30 00:09:55.290320 2020] [wsgi:error] [pid 19620] [...] File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 78, in populate [Mon Mar 30 00:09:55.290332 2020] [wsgi:error] [pid 19620] [...] raise RuntimeError("populate() isn't reentrant") [Mon Mar 30 … -
Authentication bypassing using browser cookies in Django UI
I have a view in Django which renders html page. I need to do authentication before rendering the page. The link to open this page would be provided in another application built using groovy. On clicking the link, the UI should be rendered directly without any login page. At present I am using the @login_required decorator which opens the login page before rendering the UI. I want to bypass or use another mechanism which would do the authentication without showing the login page. PS: I don't have much knowledge regarding authentication. -
Django URL : Redirect to a url having input from a form
I want the user after its registration, to redirect to a page with URL containing his/her name. I tried passing it as input in urls.py and passing name an variable in the view but its showing name variable insted of the person's name. Please help -
Compare Text and speech
Help me to build a Django project to create a website for word dictation.It is just like a list of words are there .Speak out each word,write it and evaluate. -
Django: Using a loop to output images and text from the db
I'm learning programming and following a tutorial using django 3, the same I'm using. The text and images are not displaying on the frontend on one particular html file. 1.-In settings.py I have this: MEDIA_ROOT= os.path.join(BASE_DIR,"media") MEDIA_URL= "/media/" 2.-In models.py: class Property(models.Model): title = models.CharField(max_length=200) main_photo = models.ImageField(upload_to='photos/%Y/%m/%d/') 3.-In admin.py: from django.contrib import admin from .models import Property class PropertyAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'is_published') list_display_links = ('id', 'title') search_fields = ('title', 'town') list_editable = ('is_published',) list_per_page = 30 admin.site.register(Property, PropertyAdmin) Then I migrated to the DB, I created a properties.html and the loop {{ property.main_photo.url }} or {{ property.title }} is working and getting images and texts on this properties file: {% extends 'base.html' %} {% load humanize %} {% block content %} <section id="showcase-inner" class="py-5 text-white"> <div class="container"> <div class="row text-center"> <div class="col-md-12"> <h1 class="display-4">Browse Our Properties</h1> <p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur!</p> </div> </div> </div> </section> <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> All Porperties</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if properties … -
how i can add the attribute of extra_tag in class_based_views in django
how I can add the attribute of extra_tag in class_based_views in django. in normal views we are using like this: messages.success(request, 'Product is added successfully', extra_tags='alert-primary') but in generic views how we can write it? views.py class EditProduct(SuccessMessageMixin, UpdateView): model = Product form_class = EditProductForm success_url = reverse_lazy('stock:stock') template_name = 'stock/editproduct.html' success_message = "Product is updated successfully." def form_valid(self, form): form.instance.saler = self.request.user form.instance.pub_date = timezone.now() return super().form_valid(form) Thank you for your help. -
Communication between Web and android application.(remotely control device)
I develop a website on django framework and a android app on android studio, Now what i want to do is 1- When user click on web button(trace mobile location),the mobile send the current location to the server. 2- click on web button(Ring mobile) the mobile start ringing -
How to test a view that creates a new team (entity) in a database?
I have to unit test my current project and I've hit a roadblock. I'm at 85% coverage and I need to complete this test to go further. Basically, I need to test that my view is able to create a new team in my database. The Team Model is nested under an Organization in the form of a foreign key. models.py - class Organization(models.Model): orgname = models.CharField(max_length = 100, blank=True) def __str__(self): return str(self.orgname) class Team(models.Model): teamID = models.AutoField(primary_key=True) teamName = models.CharField(max_length = 100, blank=True) org = models.ForeignKey(Organization, on_delete=models.CASCADE) def __str__(self): return str(self.teamName) views_admin.py - @csrf_exempt def newTeam(request): if request.method == 'POST': param = json.loads(request.body) orgname = param.get('org') team = param.get('team') org = Organization.objects.get(orgname = orgname) print(org) Team.objects.create(teamName=team, org=org) return JsonResponse({'status':200}) urls.py - path('ajax/newTeam/', views_admin.newTeam, name='ajax_newTeam'), I have tried this so far: def test_newTeam(self): params = {'orgname': REVCYCSCH, 'teamName': 'BLR Scheduling Eng'} response = self.client.post(path = '/ajax/newTeam/', data = params, content_type = 'application/json') self.assertEqual(response.status_code, 200) But I get this error - Error Screenshot -
Django NoReverseMatch Argument
Doesn't find a suitable url from the list(I assume it takes a string for a tuple) NoReverseMatch at /decision/livingrooms/kitchen/ Reverse for 'style' with arguments '('provans',)' not found. 1 pattern(s) tried: ['decision/livingrooms/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$'] Template <ul class="menu menu_interiors"> {% for room in rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:room' room.slug %}">{{ room.name }}</a></li> {% endfor %} </ul> <ul class="menu menu_styles"> {% for style in styles %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' style.slug %}">{{ style.name }}</a></li> {% endfor %} </ul> urls.py from django.urls import path from .views import ContactView from . import views app_name = 'decision' urlpatterns = [ path('livingrooms/', ContactView.as_view(), name='livingrooms'), path('livingrooms/<slug:rmslg>/', views.room, name='room'), path('livingrooms/<slug:rmslg>/<slug:stslg>/', views.style, name='style'), ] views.py def room(request, rmslg): styles = Room.objects.get(slug=rmslg).styles.all() print(len(styles)) return render(request, 'decision/residentialInteriors.html', {"styles": styles}) def style(request, stslg): style = Style.objects.get(slug=stslg) return render(request, 'decision/residentialInteriors.html', {"style": style}) -
Add a vaiable to each log in python logging
I have received an email through middleware, now I want to add this email in each log that I print using loggings module from different-different files from one place. How can I achieve this? -
Named volume not being created in docker
I'm trying to create a django/nginx/gunicorn/postgres docker-compose configuration. Every time I call docker-compose down, I noticed that my postgres db was getting wiped. I did a little digging, and when I call docker-compose up, my named volume is not being created like i've seen in other tutorials. What am I doing wrong? Here is my yml file (if it helps, I'm using macOS to run my project) version: "3" volumes: postgres: driver: local services: database: image: "postgres:latest" # use latest postgres container_name: database environment: - POSTGRES_USER=REDACTED - POSTGRES_PASSWORD=REDACTED - POSTGRES_DB=REDACTED volumes: - postgres:/postgres ports: - 5432:5432 nginx: image: nginx:latest container_name: nginx ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - ./src/static:/static depends_on: - web migrate: build: . container_name: migrate depends_on: - database command: bash -c "python manage.py makemigrations && python manage.py migrate" volumes: - ./src:/src web: build: . container_name: django command: gunicorn Project.wsgi:application --bind 0.0.0.0:8000 depends_on: - migrate - database volumes: - ./src:/src - ./src/static:/static expose: - "8000" -
How do I access template_context_processors?
While developing a website for an online store, I want to access the number of items added to the cart. For this I added the template_context_processors in my settings.py. But it's not showing the number of items. What could be the problem here? My views.py: def cart(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart":cart} else: empty_message = "Your cart is empty, please keep shopping." context = {"empty": True, "empty_message": empty_message} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): request.session.set_expiry(120000) try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: raise Http404 except: pass if not product in cart.products.all(): cart.products.add(product) messages.success(request, mark_safe("Product added to cart. Go to <a href='cart/'>cart</a>")) return redirect('myshop-home') else: cart.products.remove(product) messages.success(request, mark_safe("Product removed from cart")) new_total = 0.00 for item in cart.products.all(): new_total += float(item.price) request.session['items_total'] = cart.products.count() cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) Then I added this line of code to my base.html: <a class="nav-item nav-link" href="{% url 'cart' %}">Cart {{ request.session.items_total }}</a> My settings.py: """ Django settings for pyshop project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on … -
Django+AWS(Ubuntu Instance)+uWsgi+Nginx Fatal Python error: ModuleNotFoundError: No module named 'encodings'
I am deploying a django Rest API webservice in AWS and using uwsgi,inginx. Everything worked fine but webiste was not live even after running the serverConnection timed out was displayed in browser. After running this command sudo uwsgi --ini /etc/uwsgi/sites/Ftlabs.ini i got status log which says Python version: 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] !!! Python Home is not a directory: /home/ubuntu/venv !!! Set PythonHome to /home/ubuntu/venv Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named &apos;encodings&apos; Current thread 0x00007f3951cf6740 (most recent call first): Aborted As i am beginner and this is my first deployment.I searched every possible keyword but not happen to find a solution. someone please help me with that. And for reference i was following this blog post Complete Guide to Deploy Django Applications on AWS Ubuntu Instance with uWSGI and Nginx -
i m getting application error while i tried to run my app on browser , here is my logs trail
Build failed -- check your build output: https://dashboard.heroku.com/apps/e4bf9e0a-b140-4621-bff8-a3db7868ed46/activity/builds/5bc61c28-f49d-4124-bb64-00fb0fb79292 error code=H14 desc="No web processes running" method=GET path="/" host=pachalibhairav.herokuapp.com request_id=b89caaf1-1a0d-435b-83b2-835bc4cbd732 fwd="27.34.13.152" dyno= connect= service= status=503 bytes= protocol=http -
Grabbing object instance id from request.POST when using javascript e.preventDefault()
I am using a bootstrap modal to list object instances and perform CRUD operations. I wrapped the entire list in a form and pass the id of each object instances to the view using buttons names and value. When I delete the object without using Javascript, the view works fine, but as soon as I add the line e.preventDefault(); then the id of the object is not captured in the request anymore. why is that ? In more detail, the template looks like this: <form action="{% url 'delete_habit' %}" method="POST" id="deleteForm">{% csrf_token %} <div class="row"> <div class="col-12 pb-3"> <table class="modal-table border" id="habitsTable"> <tbody> {% for habit in habits %} <tr class="border js-row-{{habit.id}}"> <td class="border"> <img src="{% static 'img/bars_icon.svg' %}"> </td> <td class="text-left border px-3">{{habit.name}}</td> <td class="border"> <button id="delete-{{habit.id}}" type="submit" value="{{habit.id}}" name="habit_id" class="btn"> <img src="{% static 'img/minus_icon.svg' %}"> </button> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </form> the view: def delete_habit(request): habit_id = request.POST.get('habit_id') --> this fails when e.preventDefault() data = {'habit_deleted': int(habit_id)} habit_to_delete = Habit.objects.filter(id=int(habit_id)).filter( user=request.user) habit_to_delete.delete() return JsonResponse(data) the javascript: var deleteForm = document.getElementById('deleteForm'); if (deleteForm !== null){ deleteForm.addEventListener('submit', function(e){ var formData = new FormData(deleteForm); e.preventDefault(); --> this empties the request (except the csrf token) var request … -
Currently working on Python/Django project.I have to display ppt and doc files onto the browser but it doesnt accept the format
I have tried to you use iframe for the same.. It works well with pdf files,but unable to open ppt and doc files..Is there any solution/api's available in python/django for the same? -
How to Nested Categories in django admin
I want to create muti category in my ecommerce website where sub category will be dependent on main category. Please help me with this class MainCategory(models.Model): # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class SubCategory(models.Model): # perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True) # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class Items(models.Model): # main = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # name = models.CharField(max_length=255) Posting this question 4th time -
Using the URLconf defined in crp1.urls, Django tried these URL patterns,admin/ The current path, register.html, didn't match any of these.**
page not found error in django i got 404 error my url is http://127.0.0.1:8000/register.html and error is like Using the URLconf defined in crp1.urls, Django tried these URL patterns, in this order: [name='index'] register [name='register'] admin/ The current path, register.html, didn't match any of these. i created one folder for projects in that i started reglog application in crp1 forlder and index page i am gettting but when i click form index.html for sing up page its say aboventer code heree error in my application url file i coded: urlpatterns=[path('',views.index, name='index'),path('register', views.register, name='register')] in views file: def index(request): return render(request,'index.html') def register(request): return render(request,'register.html') and in my project name crp1 file i write following code in ''' "crp1.urls: urlpatterns' = [ path('', include('reglog.urls')), path('admin/', admin.site.urls)' ''' and in register.html ''' <a href="register.html"> </a> ''' -
my first django project and the images_url dosent load anything every thing works perfectly but but the images wont load
i am making like a demo website that sells fruits i am following a youtube tutorial by (code with mosh) his images loaded properly but my images wont other things like add to cart button and name of product loaded properly. I am very new to programming so please try not to use complex programming terms for answer and thanks to anyone who will be trying to help me. admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Product, ProductAdmin) admin.site.register(Offer, OfferAdmin) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('New products') -
How to create related objects in serializer and serialize it
Hey, I'm working in Django 2.2. I have problem with serialize data with custom create function. Let's say we have 2 models: class Model1(models.Model): a = models.CharField(max_length=200) b = models.IntegerField() class Model2(models.Model): c = models.ForeignKey(Model1, on_delete=models.CASCADE d = models.CharField(max_length=150) class Model3(models.Model): e = models.ForeignKey(Model1, on_delete=models.CASCADE) This models have serializers: class Model2Serializer(serializer.ModelSerializer): class Meta: model = models.Model2 fields = ['d'] class Model1Serializer(serializer.ModelSerializer): model2_set = Model2Serializer(many=True) class Meta: model = models.Model1 fields = ['a', 'b', 'model2_set'] def create(self, validated_data): model2_params = validated_data.pop(u'model2_set', []) model1 = super(Model1Serializer, self).create(validated_data) model2_objects = [models.Model2(model1=model1, **model2_params) for model2_param in model2_params] models.Model1.objects.bulk_create(model2_objects) return model1 class Model3Serializer(serializer.ModelSerializer): model1 = Model1Serializer() class Meta: model = models.Model3 fields = ['model1'] This custom create function is work good. My problem is that now I want to get nested data in Model3 serializer.