Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add progress bar to file uploads in Django 3 served with NGINX reverse proxy?
There are similar questions, but they are years old and address Django 1 or 2. I found some information about it and setups like the progressbarupload or this post. But it all seems to be outdated. Is there an app that works with Django 3? -
Why it doen't set DEBUG = True?
I'm working in a Django project with a venv. My problem is the next one: I've configure DEBUG = TRUE in my code below, but it seems that setting is not loaded when django is starting and it launch this error: You must set settings.ALLOWED_HOSTS if DEBUG is False. I think DEBUG is changed in the virtual environment because I debug my code and I found that DEBUG is false before starting the server import django_heroku import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DEBUG = True ALLOWED_HOSTS = [] DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] PRIORITY_THIRD_PARTY_PASS = [ 'django_admin_env_notice', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'django_filters', 'django_otp', 'django_otp.plugins.otp_totp', 'drf_yasg', ] LOCAL_APPS = [ 'finalusers', 'reports', ] INSTALLED_APPS = PRIORITY_THIRD_PARTY_PASS + DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS AUTH_USER_MODEL = 'users.CustomUser' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_otp.middleware.OTPMiddleware', ] ROOT_URLCONF = 'circulo.urls' 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', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django_admin_env_notice.context_processors.from_settings', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'circulo.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
sync_cassandra command giving error in Django
I am a complete newbie in Django & Cassandra. I am trying to connect my Django app with the Cassandra database which is running as a Docker container on port 9042 using django_cassandra_engine. This is my database settings: DATABASES = { 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'test_ks', 'HOST': 'localhost:9042', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 3 } } } } But when I run sync_cassandra command it is giving me this error: PS C:\py\pytest> python manage.py sync_cassandra Traceback (most recent call last): File "C:\Users\patil\AppData\Local\Programs\Python\Python39\lib\site-packages\django_cassandra_engine\connection.py", line 78, in register connection.get_connection(name=self.alias) File "C:\Users\patil\AppData\Local\Programs\Python\Python39\lib\site-packages\cassandra\cqlengine\connection.py", line 247, in get_connection raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name)) cassandra.cqlengine.CQLEngineException: Connection name 'default' doesn't exist in the registry. As I am completely new to Django and Cassandra I am not able to get this error. Please help me to understand and resolve this error. Thanks in advance. -
How do I set up django alongside gitlab?
Gitlab is installed on the server, it hangs on the git.domain.com subdomain, I need the site to hang on domain.com, when I try to go to this domain, the browser swears at the lack of ssl, I tried googling, I got this config # the upstream component nginx needs to connect to upstream django { server unix:///home/web/project/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8001; listen 444 ssl http2 default_server; listen [::]:444 ssl http2 default_server; server_name domain.com; ssl_certificate /etc/gitlab/ssl/domain.com.crt; ssl_certificate_key /etc/gitlab/ssl/domain.com.key; # the domain name it will serve for server_name domain.com www.domain.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/web/project/media; # your Django project's media files - amend as required } location /static { alias /home/web/project/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/web/project/deployment/uwsgi_params; # the uwsgi_params file you installed } … -
Filter pk that before url_path in ListApiView. Django
I have urlpatterns += [path('collection/<int:pk>/video/', CollectionVideoViewSet.as_view(),name='collection-videos')]. And ListAPIView: class CollectionVideoViewSet(ListAPIView): """ViewSet for operation with videos in collection""" permission_classes = (IsAuthenticated,) queryset = Video.objects.all() serializer_class = CollectionVideoSerializer Can i filter queryset in this view by pk? -
Django and ajax problem cannot show results from query in template
I'm developing a website in django and at the moment i'm trying to implement search by using ajax. Currently i'm getting results in console but i cannot show results in the template. views.py def search_products(request): if request.method == 'POST': search_str = json.loads(request.body).get('searchText') products = Product.objects.filter(Q(price__istartswith=search_str) | Q(name__icontains=search_str) | Q(description__icontains=search_str)) data = products.values() return JsonResponse(list(data), safe=False) urls.py path('search-products/', csrf_exempt(views.search_products), name="search_products"), searchProducts.js const appTable = document.querySelector(".app-table"); tableOutput.style.display = "none"; searchField.addEventListener("keyup", (e) => { const searchValue = e.target.value; if (searchValue.trim().length > 0) { fetch("/search-products/", { body: JSON.stringify({ searchText: searchValue }), method: "POST", }) .then((res) => res.json()) .then((data) => { console.log("data", data); appTable.style.display = "none"; tableOutput.style.display = "block"; if (data.length === 0) { tableOutput.innerHTML = 'No Results Found'; } }); }else { tableOutput.style.display = "none"; appTable.style.display = "block"; } }); template <div class="container-3 w-container"> <div class="search-block w-form"> <form id="email-form-2" name="email-form-2" data-name="Email Form 2" class="search-field"> <label for="name-3" class="search-label-2">Search:</label> <input type="text" class="searchfield w-input" name="name-2" data-name="Name 2" placeholder="" id="searchField"> </form> </div> </div> <div class="w-layout-grid grid-8 table-output"> <div id="w-node-_16f775a1-c8df-749b-d74e-d96c0e9465bf-488447d3" class="search-product-result"> <a href="#" class="w-inline-block"><img src="images/search-results.jpeg" loading="lazy" height="" width="237" sizes="100vw" alt=""></a> <div class="div-block-33"> <a href="#" class="link-2-product-price search">Product Title</a> <a href="#" class="link-2-product-price search">€ 500</a> </div> </div> </div> How can i show results in template by using image, product title and price … -
Why django debug toolbar is hidden?
I install django debug toolbar and it did not appear in the browser, when I looked at the code, I saw that it was hidden. How can I fix this? -
How to solve django PostCreateView is missing a QuerySet in django
here we go screen shot of the above mentioned problem enter image description here -
Testing absolute url for models in django
in my model for userprofile. def get_absolute_url(self): return reverse('user_detail', kwargs={'pk': self.pk}) in my test.py def test_get_absolute_url(self): user = UserProfile.objects.get(id=1) self.assertEqual(user.get_absolute_url(), '/writecloud/user/1') well i wanna know if what i wrote in assertEqual() is correct to test this. im not sure how to use kwargs -
Use raspberry pi as server with custom domain for django project
I found a way to set up my raspberry pi for custom domain. Than he takes the /var/www/index.html as html file. But I want it to go to my django project. I set u an apache server, but i don't realy know how to link all those. It works separate, but not togheter. Any video or post how to set this up? -
How to Solve This Problem Which Picture is given below
This error found in django oscar. when i edit basket.html -
How to make a "create-only" non-editable field in django admin
im looking for some solution about make a "create-only" field on django admin using models. I saw some questions before, but no one can answer the core question: the field should appear when the user are creating on admin panel, but i dont want to be able to edit. models.py class Fonte(Always): source_slug = models.CharField(max_length=255) admin.py @admin.register(Fonte) class FonteAdmin(admin.ModelAdmin): readonly_fields = ['source_slug'] the "readonly_fields" solves the problem in the matter of editing in the future, but ends up forbidding when creating. Problem: Im using this field to make a hash and i dont wanna this change evermore.. I thought about using a second field that would generate a hash on top of the editable one field in the creation, after that the field would be "dead", but that seems to me to be contrary to the 2 way of normalization. Is there any more elegant way? -
NoReverseMatch at / 'customer' is not a registered namespace
This is a follow-on question from my answer to Django-oscar : how to change the URL from root APP?. Working through the Frobshop tutorial, I encountered an error when I attempted to subclass a template. The message was: NoReverseMatch at / 'customer' is not a registered namespace. The Problem Essentially, there is a problematic path() or repath() invocation, and to resolve the issue a namespace parameter needs to be provided to the invocation in urls.py: path(pattern, include([app_urls]), <i>... or ...</i> re_path(pattern, include([app_urls]), High-Level Solution I believe there is a conceptually simple solution, however the details are tricky. The solution has two key points: This part is easy. The offending path or re_path method require namespace and app_name parameters. To do this a 2-tuple need to be provided as the first argument for include(). Conceptually, the 2-tuple looks like ([app_urls], app_name), where the first item in the tuple is an app's array of URLs, and the second item in the tuple is the name of the app. Now for the tricky part. When one django-oscar path is redefined, some other app paths must also be redefined. You can see all of the registered apps by setting a breakpoint in get_app_config() in … -
How to add, retrieve and update fields which are not implemented in models using djongo?
I am using mongoDB as my primary database in a django project. I am using djongo engine for accessing and manipulating mongoDB. For testing I wrote a simple student model class StudentModel(models.Model): name = model.CharField(max_length=250) age = model.IntegerField() and insereted data to this model using from app.models import StudentModel StudentModel(name="John" age=10).save() Because mongoDB is schemaless database I want to try and add fields which are not implemented in StudentModel, I have tried to insert a new student with additional email address field. StudentModel(name="Steve" age=9, email="steve@email.com").save() But it gives this type error TypeError: StudentModel() got an unexpected keyword argument 'email' This is my database setup in settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'testdb', 'ENFORCE_SCHEMA': 'False', } } How do we add, retrieve and update fields which are not implemented in models using djongo? -
Invalid template library specified. No module named 'crispy_forms.compatibility'
Every time I try to run my django application locally on localhost using python3 manage.py runserver, ge thte following error and i dont understand why. I have the latest version of crispy forms installed (1.11.2) and i have it on my requirements.txt, and installed on my venv. Can someone help me? Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/Users/bermed28/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/crispy_forms/templatetags/crispy_forms_filters 2.py", line 9, in <module> from crispy_forms.compatibility import lru_cache ModuleNotFoundError: No module named 'crispy_forms.compatibility' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/bermed28/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/bermed28/opt/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File … -
How do I copy existing formset data to prepopulate a CreateView in Django?
In one of my views, I use a class based CreateView to prepopulate my form with various fields from a different model. I do so like shown below: def get_initial(self): initial = super(Author, self).get_initial() book = Book.objects.get(pk=self.request.GET.get("dropdown")) initial = Book.__dict__.copy() initial.update({ "pages": book.pages, return initial Works brilliantly. Now I'm trying to grab data from some related formsets for this model as well, but because they are formsets, I'm a bit stumped on how to go about doing the prepopulation in as close to an identical fashion as possible. They are inline formsets. I've spent the last day looking and can't find anything that is helping me think this through. Thanks in advance for any thoughts on this. -
How to bypass WSGI error in django filter
from django.db import models from django.contrib.auth.models import User class Transfer(models.Model): id = models.AutoField(primary_key=True) amount = models.DecimalField(max_digits=10, decimal_places=2) name=models.CharField(max_length=55) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) Is it possible to make a request like this without WSGI error? result = Transfer.objects.filter(name=request.name) -
OperationalError at / no such table: blog_post
I'm making a Blog in Django. But when I run my program it gives me this error: OperationalError at / no such table: blog_post. I tried deleting migrations and db.sqlite3 table and ran the migrations command but it didn't work. Here is my code: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='Published') class Post(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) title = models.CharField(max_length=255) body = models.TextField(null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique_for_date='publish') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='Draft') tags = TaggableManager() objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) def __str__(self): return self.title class Meta: ordering = ('-publish',) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.CharField(max_length=255) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f"Comment by {self.name} on {self.post}" class Meta: ordering = ('-created',) views.py from django.shortcuts import redirect, render, get_object_or_404 from django.core.mail import send_mail from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from taggit.models import Tag from django.db.models import Count from django.contrib.auth.decorators … -
forms in django dose not retrive data and save it
i'm trying to create an appointment app with multiple condition in theory i find a way to make it happend but it dose not save the data an give me an error message the first part of the code work perfectly the 2nd part dose not save any data i try a lot of things but nothing work this is my code mybe some one see where the error is and give a hint to fix this this is my views.py @login_required def create_appointement(request): user = User() ######################################################"this part work perfectly if request.user.is_patient(): form_appointement = AppointmentForm(request.POST or None) if request.method=='POST': form_appointement = AppointmentForm(request.POST or None) if form_appointement.is_valid(): form_app = form_appointement.save(commit=False) form_app.user_ho_add = request.user form_app.patient = request.user # form_app.end_time = (form_app.start_time)+(timezone.timedelta(minutes=30)) # end_time_time = datetime.combine(form_app.start_time, time()) + timedelta(minutes=30) # form_app.end_time = end_time_time.time() start_time = form_app.start_time future_time = dt.datetime(1970, 1, 1, start_time.hour, start_time.minute, start_time.second, start_time.microsecond) + timedelta(minutes=30) form_app.end_time = dt.time(future_time.hour, future_time.minute, future_time.second, future_time.microsecond) form_app.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement1.html',{'form':form_appointement}) ###################################### this the part that give me always the error message and dont save any data else: if request.method=='POST' and request.POST.get("type") == "register patient": form_appointment_2 = AppointmentForm_2(request.POST or None) user = User() user2 = get_user_model() patients = user2.objects.filter(type_of_user=TypeOfUser.PATIENT) if form_appointment_2.is_valid(): … -
Django "Join" and "count" - Easy in psql, not so trivial in Django
user id 8a0615d2-b123-4714-b76e-a9607a518979 has many entries in mylog table. each with an ip_id field. I'd like to see a weighted list of these ip_id fields. in sql i use: select distinct(ip_id), count(ip_id) from mylog where user_id = '8a0615d2-b123-4714-b76e-a9607a518979' group by ip_id this gets me: ip_id count --------------------------------------+-------- 84285515-0855-41f4-91fb-bcae6bf840a2 | 187 fc212052-71e3-4489-86ff-eb71b73c54d9 | 102 687ab635-1ec9-4c0a-acf1-3a20d0550b7f | 84 26d76a90-df12-4fb7-8f9e-a5f9af933706 | 18 389a4ae4-1822-40d2-a4cb-ab4880df6444 | 10 b5438f47-0f3a-428b-acc4-1eb9eae13c9e | 3 Now I am trying to get to the same result in django. It's surprisingly elusive. Getting the user: u = User.objects.get(id='8a0615d2-b123-4714-b76e-a9607a518979') #this works fine. I tried: logs = MyLog.objects.filter(Q(user=u) & Q(ip__isnull=False)).value('ip').annotate(total=Count('ip', distinct=True)) I am getting 6 rows in logs which is fine, but the count is always 6, not the weight of the unique ip as it is in the SQL response above. What am I doing wrong? -
How are messaging apps like Whatsapp or Messenger built?
I'm trying to build a mobile messaging app like Whatsapp and don't know where to start. In the first place, I don't know how messaging apps send messages between users. What type of protocol do they use? Do they use websockets? Do they use some sort of long polling? I mean what I really want to know is how the server works and is there a name to this sort of communication? FYI, I was looking to try and build a messaging app with a Django (something like django channels) server and React native for the mobile app. Thanks for reading. -
Loading specific foreign key attribute in Django Template
Devs, I have a 2 Models and one of them have a foreign key attribute as a reference to the other. Now I am trying to view both objects in my Template. class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(self, **kwargs): context = super(ItemDetailView, self).get_context_data(**kwargs) context['markets'] = Market.objects.all() # And so on for more models return context In my template I just want the exact market for my product I tryed something like this: {% for market in markets %} // or {% for object.market in markets %} {% if market.market == object.market %} >> Do smth if conditions match << {% endif %} {% endfor %} In the loop I get strings like x1, x2, x3 and object.market have the value x1. So I just want to output x1. -
How do you add a LoginRequiredMixin when there's an inconsistent method resolution?
I have the following urls.py file: urlpatterns = [ path('', views.index, name='index'), path('account/', include('django.contrib.auth.urls'), name="login"), path('signup/', views.SignUp.as_view(), name='signup'), path('polls/<int:pk>/', views.DetailView.as_view(), name='detail'), path('polls/<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('polls/<int:week_id>/vote/', views.vote, name='vote'), ] And the following views: @login_required def index(request): return HttpResponse("Hello, there my frined") class SignUp(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class DetailView(LoginRequiredMixin, DetailView): model = Week template_name = "detail.html" # Problem is here class ResultsView(LoginRequiredMixin, DetailView): model = Week template_name = 'results.html' For some reason the LoginRequiedMixin in the ResultsView class produces the following error: File "/Users/user/Projects/cafeteria/weeklydesert/urls.py", line 3, in <module> from . import views File "/Users/user/Projects/cafeteria/weeklydesert/views.py", line 25, in <module> class ResultsView(LoginRequiredMixin, DetailView): TypeError: Cannot create a consistent method resolution order (MRO) for bases LoginRequiredMixin, DetailView This is my results.html <h1>Week of: {{ week.coming_monday }}</h1> <ul> {% for choice in week.choice_set.all %} <li>{{ choice.desert_choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'detail' week.id %}">Vote again?</a> The code runs fine when removing the mixin form ResultsView, what's wrong with the code? -
Best way to use Python classes for creating Stripe objects and handling errors
I have a Django application that integrates with Stripe. Per the Stripe documentation, I am following their recommendation to use try/except clauses to handle any errors that might arise during the process of creating customers, products, prices, etc. To keep things DRY, I have made a base Python class from which object-specific subclasses inherit. This way I can customize the create_method of each subclass to create a particular object, but still keep all the error handling in one place (the parent class). This all seems to be working fine, but I'm wondering if anyone has any feedback or suggested improvements for this approach? Thanks! import stripe from django.conf import settings stripe.api_key = settings.STRIPE_SECRET_KEY class StripeObject(): """ Base class for all Stripe objects (e.g., Customer, Product, Price) """ create_method = None def __init__(self, common_kwargs={}, instance_kwargs={}): self.common_kwargs = common_kwargs self.instance_kwargs = instance_kwargs def handle_error(e): try: print('Code is: %s' % e.code) print('Message is: %s' % e.user_message) except KeyError: print('One of the following keys was not found in the error response:\ncode or user_message.') def create(self): try: return self.create_method(**self.common_kwargs, **self.instance_kwargs) except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly self.handle_error(e) except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to … -
Different title and description tags for Django site with pagination
I have a web site running on django and use pagination for some of my pages. Search engines demand different title and description tags for every page. Is it possible somehow differentiate title and description tags for different pages with similar name (https://bratus.net/listings/?page=2), for example using part of pagination code in title ? Thank you !!!