Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select latest record for each hour
I have Balance model Each balance has b_date = models.DateTimeField() I parse balances every 5 mins but to user I want to show latest balance of each hour So for example if I have balances with #1 b_date="15:34", #2 b_date="15:55, #3 b_date="20:00" the output should be: #2 b_date="10.06.15 15:55 #3 b_date="11.07.15 20:00" As you can see we removed balance #1 because we need only latest balance from each hour. So far I've come to this: trunc_entries = balances.annotate(tx_hour=TruncHour('b_date')) Which sets all hours to 00:00 But I don't know how to group by this tx_hour and select latest -
Why does my browser keep redirecting to the index and not the views?
Please excuse me if I forget to include any necessary code as it's my first post. I've been trying to get this code from the "Writing your first Django app" to work, I have no clue what I'm doing wrong.(Please do keep in mind that I am using Python 2.7 and Django 1.11 which is why I have url rather than path) Here is my polls\urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^', views.index, name='index'), url(r'^<int:question_id>/$', views.detail, name='detail'), url(r'^<int:question_id>/results/$', views.results, name='results'), url(r'^<int:question_id>/vote/$', views.vote, name='vote'), ] And here is my mysite\urls.py: from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] Please let me know if I am missing any necessary code to provide context, thank you. -
why my Python Django urls is not working?
I am working on a python django website and my urls are not working properly. I have included my urls.py and the nav links which are the same on each page. Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name='products'), path('customer/<str:pk_test>/', views.customer, name="customer"), ] navbar.html: {% load static %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <img src="{% static 'images/logo.png' %}"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Dashboard</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'products' %}">Products</a> </li> </ul> </div> </nav> -
Django like filter-horizontal widget in ReactJS?
I fell in love with simplicity of django filter horizontal widget. It looks something like this Django admin interface: using horizontal_filter with ManyToMany field with intermediate table This time I am creating some app in ReactJS and would like to know if there exists some package that looks and works like this? I have been googling around React Filter horizontal or React Select multiple but can't seem to find what I am looking for. Thanks for your help. -
return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable
I was making one webapp in django. I try to deployed it on pythonanywhere everything was going fine but in last when i tried to collect static files using python manage.py collectstatic it is giving me this error: return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable suggest some idea how can I solve it. Here is my setting.py file import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!25%rdt-$_$bsc*fl)e7x2*x6awjca^3_2t-k@l0tu*8k!f33&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR / 'static/') -
Wagtail search doesn't work inside i18n_patterns
I've added a wagtail-modeltranslation to my site. Everything works as it should despite the search. When the search is inside the the regular urlpatterns - it redirects only on LANGUAGE_CODE version of the site, but when i put it in the i18n_patterns - search stops working and raises 404 error. Why is it so and how to fix it? -
Refresh a div in Django using JQuery and AJAX - Django ForLoop Issues
I have a django project that I'm trying to add a custom "online" state to (boolean field in a model). I want to refresh a div periodically to show if a user is now online. The div which is refreshed, with the class button-refresh, is in an included HTML file. The issue is that the include doesn't work with my for loop in the original HTML file, none of the "professionals" data is retrieved from the server. I'm pretty new to django, my assumption is that the refresh_professionals.html file is retrieved with the ajax request and is entirely separate from the all_professionals.html and then included, without ever being a part of the for loop meaning that the {{ professional.professional_profile.online }} syntax doesn't work. Any ideas on how to fix this issue? If there is a better way to do this, let me know. Thanks. all_professionals.html {% for professional in professionals %} ... {{ professional.name }} {% include 'professionals/refresh_professionals.html' %} ... {% endfor %} ... {% block postloadjs %} {{ block.super }} <script>var global_url = "{% url 'refresh_professionals' %}";</script> <script src="{% static 'professionals/js/professionals.js' %}"></script> {% endblock %} refresh_professionals.html <div class="col button-refresh"> {% if professional.professional_profile.online is True %} <p class="custom-button mb-1 w-25 … -
When running pip freeze in Git Bash - TypeError: 'module' object is not callable
When using Git Bash and running anything with pip: pip freeze I get this error: Traceback (most recent call last): File "c:\program files (x86)\python38-32\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\program files (x86)\python38-32\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Program Files (x86)\Python38-32\Scripts\pip.exe_main.py", line 9, in TypeError: 'module' object is not callable I am coming back to this code to deploy on Heroku. But now getting stuck at this stage, which wasn't happening before... -
My catalog app shows a blank page, what should I do?
I'm creating a website in django, and currently I'm building a online catalog of items. But when I run it, it just shows a blank page. my code is given below: catalog\models.py from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=40, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class itemType(models.Model): name=models.CharField(max_length=40) def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog:item_list_by_category', args=[self.slug]) class itemStage(models.Model): name=models.CharField(max_length=10) def __str__(self): return self.name class item(models.Model): name=models.CharField(max_length=20, help_text='Name of the item', db_index=True) slug = models.SlugField(max_length=200, db_index=True, null=True) description = models.CharField(max_length=200, help_text='Description', blank=True, db_index=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) version=models.CharField(max_length=20, help_text='Version of the item') pub_date=models.DateTimeField('date', help_text='The date of publishing', auto_now=True) item_type = models.ForeignKey(itemType, on_delete=models.SET_NULL, null=True) stage = models.ForeignKey(itemStage, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to = 'static/static_dirs/images', blank=True) def __str__(self): return self.name class Meta: ordering = ('name',) index_together = (('id', 'slug')) def get_absolute_url(self): return reverse('catalog:item_detail', args=[self.id, self.slug]) catalog\views.py from django.shortcuts import render # Create your views here. from .models import item, itemType, itemStage def itemListView(request, category_slug=None): num_items = item.objects.all().count num_types = itemType.objects.all().count if category_slug: category = get_object_or_404(Category, slug=category_slug) items = items.filter(category=category) context = { 'num_items' : … -
How to tag the whole ViewSet in drf_yasg?
I have the following ViewSet: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer permission_classes = [permissions.AllowAny] # note that no methods are overridden I want drf_yasg to generate custom schema such that all action methods will be tagged as Authors. The documentation says that my options are to either decorate each method by declaring it and using @swagger_auto_schema like so: class AuthorViewSet(viewsets.ModelViewSet): # ... @swagger_auto_schema(tags=["Authors"]) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) Or use Django's @method_decorator like so: @method_decorator(name="list", decorator=swagger_auto_schema(tags=["Authors"])) class AuthorViewSet(viewsets.ModelViewSet): # ... Both options require tedious repetition which I would like to avoid. I've also tried to implement my own decorator: def decorate_viewset_methods(names, decorator): if names == "__all__": names = [ "create", "retrieve", "update", "partial_update", "destroy", "list", ] def decorate(cls): for name in names: method = getattr(cls, name) setattr(cls, name, decorator(method)) return decorate But it didn't quite work out. So my question is how can I decorate all action methods at once? -
How do I authorize a user without a form?
I have a nice user login web page, it has input fields ( tags) for login and password and decorative design elements. There is also a button to enter ( tag). From the point of view of HTML, this is not a form, because the page does not have the "FORM" tag and the "SUBMIT" button. How can I sign in for a user without making any changes to the web page? I can process the scripts, but I'm not sure if this is the right approach for solving my problem (do not forget that this is a login page and I will need to pass a password). I can authorize a user using Django forms (and, as a consequence, a HTML form), but how can I do this without a HTML form? -
Django through model not saving in admin
I created a through model in django {code snippet} and i have registerd it through admin, there is no problem there and its shown in the admin panel. But when i enter data in the admin pannel and click save its showing this. "The more edu info “MoreEduInfo object (None)” was added successfully." and there is no data saved in the admin. what am i doing wrong.? -
Nested for loop in Django Template not able to loop through a dictionary item
Part of a small ecommerce project I'm trying to build. The views.py function that displays the order_info @login_required def past_orders_view(request): print (request.user) allOrders = Order.objects.filter(full_name=request.user) return render(request, "orders.html", {'Orders':allOrders}) The allOrders queryset from db looks like, which will display the orders for the particular logged in user: <QuerySet[<Order: 13-{'Zenbook 14': '82990.00', 'iPhone 11 64gb': '61999.00'}-godric-+919871199215>]> In template, I have something like this: <table class="table table-striped"> <head> <tr> <th> Ordered Date </th> <th> Status </th> <th> Product Name </th> <th> Price </th> </tr> </thead> <tbody> {% for order in Orders %} <tr> <td> {{order.date}} </td> <td> {{order.status}} </td> <td> {{ order.items_json.XXXX}} </td> <td> {{ order.items_json.XXXX }} </td> </tr> {% endfor %} </table> Also, in view.py the model object for Order saves these info when placing an order order = Order(items_json=items_json, full_name=name, town_or_city=city, phone_number=phone, status=status, date=timezone.now()) order.save() So, the Order objects such as full_name, status, date can be directly accessed through a for loop in the template, and displayed as desired in the HTML. The problematic part is looping through the dictionary which has product name as key, and it's price as the value. Already tried nested for loops, couldn't get the answer. Tried loop sample: {% for order in Orders %} … -
Make permission bypass for Ajax requests from my website in Django Rest Framework
I made this API permission def has_permission(self, request, view): return request.user.is_authenticated and ( request.user.is_superuser or models.AllowedToUseAPIList.objects.filter(user=request.user).exists() ) where I check if user who asks for API is added into list of AllowedToUseAPIList. But I also need to make AJAX requests from other pages of this website to this API. How can I change the permission to allow doing that? I also pass my CSRF token into AJAX call but get 403. -
Show all articles from specific category [django]
I want show all Articles from specific category in my template 'category_articles.list.html' at the link: path('category/<name_of_category_SLUG>/' I have: URLS urlpatterns = [ path('show/<int:pk>/<slug:slug>', ArticleDetailView.as_view(), name='article_detail'), path('all/', AllArticlesListView.as_view(), name='all_articles_list'), path('category/<slug:slug>/', CategoryArticlesList.as_view(), name='category_articles_list'), ] MODELS class Created(models.Model): created_on = models.DateTimeField(auto_now_add=True, null=True) class Meta: abstract = True class ArticleCategory(Created): category_name = models.CharField(max_length=128) slug = models.SlugField(null=False, unique=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.category_name) return super().save(*args, **kwargs) def __str__(self): return self.category_name class Meta: verbose_name_plural = 'Article categories' class Article(Created): title = models.CharField(max_length=120) author = models.ForeignKey(User, on_delete=models.CASCADE) snippet = models.TextField(null=False) # ustawić max_lenght body = RichTextField(null=False) category = models.ManyToManyField(ArticleCategory, related_name='articles') # TODO: ustawić on_delete image = models.ImageField(blank=True, null=True, upload_to='article_image/') slug = models.SlugField(null=False, unique=False) def save(self, *args, **kwargs): # opisać tą funckję if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def get_absolute_url(self): return reverse('news:article_detail', kwargs={'pk': self.pk, 'slug': self.slug}) def article_categories(self): # zwraca nam wszystkie kategorię artykułu w stringu return ", \n".join([x.category_name for x in self.category.all()]) def __str__(self): return f"{self.title}" class Meta: verbose_name_plural = 'Articles' VIEWS class CategoryArticlesList(DetailView): template_name = 'news/category_articles_list.html' model = ArticleCategory class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 2 def get_queryset(self): return self.model.objects.all().order_by('-created_on') class ArticleDetailView(DetailView): template_name = 'news/article_detail.html' model = Article ARTICLES_LIST.HTML template ALL NEWS {% if … -
ExpressJS 4.x: simply render index.html with variables (like in Django)
Very simple question I can't find answer for. Using ExpressJS 4.x I would like to do: app.get('/', function(req, res) { res.render('index.html', {name:"Peter"}); }); And then my index.html I want it to be like: <!DOCTYPE html> <html> <body> <h1>Hello {{ name }}</h1> </body> </html> I want to write plain HTML (no pseudo html like pug, ejs, etc.), just plain html with the addition of variables this way: {{ variable }} Is this possible?? It must be easy... Thank you very much for you help!! -
Question about django url.py problem, please help me
While creating a website using django, the following problem occurred. In the case of A url, it does not work, and in the case of B url, it works fine, but I do not know why. I guess it's because of /, but please give your opinion. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('movies/', include('movies.urls')), ] urls.py(app) from django.urls import path from . import views app_name = 'movies' #A path('recomma-recommend/', views.recommand_movie), #does not work #B path('recomma-recommend/asd/', views.recommand_movie), #work -
How to implement cross join in django for a count annotation
I present a simplified version of my problem. I have venues and timeslots and users and bookings, as shown in the model descriptions below. Time slots are universal for all venues, and users can book into a time slot at a venue up until the venue capacity is reached. class Venue(models.Model): name = models.Charfield(max_length=200) capacity = models.PositiveIntegerField(default=0) class TimeSlot(models.Model): start_time = models.TimeField() end_time = models.TimeField() class Booking(models.Model): user = models.ForeignKey(User) time_slot = models.ForeignKey(TimeSlot) venue = models.ForeignKey(Venue) Now I would like to as efficiently as possible get all possible combinations of Venues and TimeSlots and annotate the count of the bookings made for each combination, including the case where the number of bookings is 0. I have managed to achieve this in raw SQL using a cross join on the Venue and TimeSlot tables. Something to the effect of the below. However despite exhaustive searching have not been able to find a django equivalent. SELECT venue.name, timeslot.start_time, timeslot.end_time count(booking.id) FROM myapp_venue as venue CROSS JOIN myapp_timeslot as timeslot LEFT JOIN myapp_booking as booking on booking.time_slot_id = timeslot.id GROUP BY venue.name, timeslot.start_time, timeslot.end_time I'm also able to annotate the query to retrieve the count of bookings for which bookings for that combination … -
Django-Form: Problem with adding additional information to form while cleaning it
I've got a Django form which simply takes a zip-code. class ServiceAreaForm(forms.Form): name = forms.CharField(disabled=True, required=False) zip = forms.IntegerField( label="PLZ", validators=[validateZipCodeLength] ) def clean(self): service_area: ServiceArea = validateServiceArea(self["zip"].value()) self.fields["name"].value = service_area.name super().clean() In validateServiceArea, I would like to check the zip code is supported. def validateServiceArea(zip_code): try: return ServiceArea.objects.get(zip=zip_code) except ServiceArea.DoesNotExist: raise ValidationError("Not supported Service Area") If so, I would like to pass the information in my returned ServiceArea on to another form, instead of using another query for the same thing. I've been trying using the clean method of the form and put it in the name-field, but it just feels too complicated (and name won't even appear in cleaned_fields). Is there any easy way doing this? -
How to fix a “413 request entity too large” on digital ocean-django app
I recently deployed a django app to digital ocean using gunicorn and nginx, the app is working but while trying to upload files, it threw an error 413 request entity too large. I've tried some suggestions on this stackflow which state that there is need to add client_max_body_size to /etc/nginx/nginx.conf, when I did this, an error client_max_body_size directive not allowed in /etc/nginx/nginx.conf was thrown. I really do not know what to do, kindly help. -
What is this User parameter in Django?
What is the User model we are importing here? What does it do here? from django.contrib.auth.models import User class Customer(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) phone=models.CharField(max_length=200, null=True) email=models.CharField(max_length=200, null=True) profile_pic=models.ImageField(default="profile2.png",null=True,blank=True) def __str__(self): return self.name -
Django restframework photo upload error while PUT method?
I am trying to upload an image using Django Django REST framework API using PUT method,but when i send to multipart/data in request its shows that i am sending data but when see response it empty, However, If I send data with the json file name and category take and file shows empty or null in request or in reponse file is null, and when i send data with the multipart/data using formData in react js its shows like this you can see in image. Request data shows that i am sending image Response shows empty Here is my models.py class BlogPhoto(models.Model): blog = models.ForeignKey(Blog, models.CASCADE, verbose_name=_('blog')) name = models.CharField(_("Description about image"),max_length=255, null=True, blank=True) file = models.ImageField( _("Upload documents image"), null=True, blank=True, upload_to=generic_upload_blog, max_length=500 ) views.py class BlogImagel1View(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthenticated,) serializer_class = PhotoBlogSerializer parser_classes = (MultiPartParser, JSONParser) def get_queryset(self): return Blog.objects.all() serializers.py class BlogPhotoSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) file = serializers.ImageField( max_length=None, use_url=True, allow_null=True, allow_empty_file=True,) class Meta: model = BlogPhoto exclude = ['blog'] def get_file(self, obj): if obj.file: return self.context['request'].build_absolute_uri(obj.file.url) class PhotoBlogSerializer(serializers.ModelSerializer): blog_photo = BlogPhotoSerializer( many=True, source="blogphoto_set", required=False ) class Meta: model = Blog fields = ["blog_photo"] def create(self, validated_data): if "blogphoto_set" in validated_data: cps = validated_data.pop("blogphoto_set") else: cps = … -
using if statment with modles field django
I'm trying to use if statement in the template but it doesn't work in template: {% for post in posts %}{% if post.tag == 'book' %} <div class="product-item "> <div class="pi-pic "> <img src="{{post.Img.url}} " alt=" "> {% if post.tag %} <div class="sale ">{{post.tag}}</div> </div></div> {% endif %}{%endfor%} in modles.py : class Post(models.Model): title = models.CharField(max_length=200,null=True) Img = models.ImageField(upload_to='images/',null =True) tag=models.ForeignKey('tags',on_delete=models.CASCADE, null=True) class tags(models.Model): tag_name= models.CharField(max_length=100) def __str__(self): return self.tag_name -
Running python manage.py run_huey in production
I recently deployed a django web app using Ubuntu 20.04, gunicorn and nginx, Huey was implemented which worked perfectly locally. At production, I need to run python manage.py run_huey using systemd. I've tried the suggestion here Can't enable huey service on deploy server but not working. My code is similar to that suggestion. I will appreciate any contribution. Thanks in advance -
Resolve actual request host in docker container
I have my entire dockerized application up and running with following tech stack Django Gunicorn Postgres Nginx Celery Redis My application deals with twitter apis so it needs to generate a callback url that consists of the current host (where the application is running, in development this is my local machine). Let the correct callback url be http://xyz.ngrok.io (i am using ngrok for some purpose). The request.build_absolute_uri() in django will generate the above url in normal scenario. But as i am using docker, the url generated is http://web. This web is the name of my service as defined in docker-compose.yml file. In nutshell, i want the actual request host uri and not the docker service name. I don't consider myself good with networking, please ignore incorrect terms if used.