Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to list distinct sqlite queryset in django
I'm trying to get all unique values of a certain field of a Django model. Unfortunately sqlite doesn't support DISTINCT on fields so the following didn't work dates = Invoices.objects.distinct('invoice_date') so I've tried this dates = Invoices.objects.values_list('invoice_date').distinct() what looked good on first sight because dates.count() returns the amount of unique values. However len(dates) still returns the total number of dates and when I transform it into a list (to be able to build a JSON response) via list(dates) I end up with all dates :/ How can get that list of uniques values? Or is it impossible with sqlite? -
RSS to html bootstrap
good night, i have a link with direct access to an rss that gets me weather information for a certain city. How is it possible from rss to make a web page with these rss? I was looking but I didn't find information to help me i create a class name weather class WeatherFeed(Feed): title = "meteorology" link = "https://weather-broker-cdn.api.bbci.co.uk/en/forecast/rss/3day/2742611" description = "meteorology" def items(self): return Post.objects.filter(status=1) def item_title(self, item): return item.title def item_description(self, item): return truncatewords(item.content, 30) I don't know what I have to do anymore -
How to use DRF serializer with djongo in Django?
I'm using djongo with Django in order to be able to use MongoDB. But there seems to be a small problem that I cannot fix. I have such model: class Company(models.Model): _id = models.ObjectIdField(primary_key=True) STATUS_CHOICES = [ (0, "active"), (1, "inactive"), ] status = models.IntegerField(choices=STATUS_CHOICES, null=False, blank=False) name = models.TextField(unique=True, null=False, blank=False) short_name = models.CharField(max_length=40, default=None) description = models.TextField(null=False, blank=False) profile_image = models.ImageField(default=None, upload_to=company_directory_path) owners = models.ArrayField(model_container=Person, default=[]) staff = models.ArrayField(model_container=Employee, default=[]) roles = models.ArrayField(model_container=Role, default=[]) address = models.EmbeddedField(model_container=Address, null=False, blank=False) localizations = models.ArrayField(model_container=Address, default=[]) LEGAL_FORM_CHOICES = [ (0, "jednoosobowa działalność gospodarcza"), (1, "spółka cywilna"), (2, "spółka jawna"), (3, "spółka partnerska"), (4, "spółka komandytowa"), (5, "spółka komandytowo-akcyjna"), (6, "spółka z ograniczoną odpowiedzialnością"), (7, "spółka akcyjna"), (8, "fundacja"), (9, "szkoła/uczelnia wyższa"), (10, "inne"), ] legal_form = models.IntegerField( choices=LEGAL_FORM_CHOICES, null=False, blank=False ) nip = models.CharField(max_length=10, null=False, blank=False) pkd = models.CharField(max_length=11, choices=PKD_OPTIONS, null=False, blank=False) created_at = models.DateField(blank=False, null=False, auto_now_add=True) objects = models.DjongoManager() def __str__(self): return self.name (Person, Employee and Role models are abstract) I have this view set: class CompanyViewSet(CustomViewSet): """The viewset for the User model.""" queryset = Company.objects.all() # mapping serializer into the action serializer_classes = { "list": CompanyListSerializer, "retrieve": CompanyDetailSerializer, "update": CompanyUpdateSerializer, "create": CompanyDetailSerializer, } default_serializer_class = CompanyListSerializer def get_serializer_class(self): return … -
Problems adding multiple data in one field
I am developing an application where a task is assigned to a developer and each task has different activities, the scare is that I am trying to add several activities per task but I can only add one, I have tried ajax but it did not work This is my model class Task(models.Model): developer = models.ManyToManyField(Developer) type_task = models.ForeignKey(TypeTask, on_delete=models.CASCADE) task = models.CharField(max_length=50) description = models.TextField() state = models.BooleanField(default=True) slug = models.SlugField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Activities(models.Model): name = models.CharField(max_length=50, unique=True) task = models.ManyToManyField(Task) this is my view class TaskCreateView(PermissionRequiredMixin, LoginRequiredMixin, CreateView): login_url = 'users:login' permission_required = 'tasks.can_add_user' template_name = 'tasks/add_task.html' form_class = TaskForm model = Task success_url = reverse_lazy('tasks:task') -
Django/wsgi not serving media files properly
I'm developing a small web GIS app with Django just for demo purposes. Everything works fine with static and media files when Debug=True, but when I set Debug to False in production and want to serve static and media files through the web server (apache), using wsgi, I get 404 when sending a request to fetch the .tiff files from media folder (but files are there, I've checked the paths a million times). I know it's not a good idea to serve .tiff files from media folder and from the same server Django uses, I know I should dedicate a different server for media and static files or use AWS S3 buckets (which is a plan for the future), but this is only a demo/presentation/PoC kind of an app and I want to know what am I doing wrong. A working scheme is pretty straightforward, I process some images (geotiffs), store them locally in data folder (which is defined as a media folder in my project), save the path in PostgreSQL database and render it in frontend. Like I said, everything works fine in production when Debug=True, but when I change it to False for security reasons, only media files … -
Random default value for a related model Django
I got a model Car and model Bumper related to Car . How can I set the default value of a Bumper's car to a random Car object in Django ? -
alpine.js $dispatch modal -> submit Form
I am using django and i have a base template where i defined a modal using alpine.js with $dispatch sender. base.html: <div x-data="modal()" class="mt-6" x-cloak> <template x-on:show-modal.window="isOpenModal = $event.detail.show; modalHeader = $event.detail.modalHeader; modalData = showData($event.detail.modalData); "></template> <div class="absolute z-50 top-0 left-0 w-full h-full flex items-center justify-center bg-black bg-opacity-50" x-show="isOpenModal"> <div class="z-50 text-left bg-gray-200 px-4 shadow-xl rounded-lg mx-2 md:max-w-lg md:p-6 lg:p-8 md:mx-0 h-auto " > <div class="flex justify-between"> <h2 id="modalHeader" class="text-2xl" x-text="modalHeader"> </h2> </div> <div class="w-full border border-gray-600 mt-4" ></div> <div id="modalContent" class="text-lg w-auto" > </div> </div> </div> </div> in script tags .... function modal(){ return{ isOpenModal: false, modalHeader:'', modalData: '', showData(data){ document.getElementById('modalContent').innerHTML = data let fp = flatpickr(".pickerDate", {locale: "at", dateFormat: "d.m.Y"}); }, } } then in the other html which is extendet from the base.html i want to use the modal where i want to get with axios form data from the server and put it into the modal. This is working perfect. But i don't know how to realize the submit button ? new.html <div x-data="test()" @click="getCreateForm($dispatch)"> test click </div> this is the point where i go to function getCreateForm .... function test(){ return{ getPatientCreateForm($dispatch){ axios.get("{% url 'user:createForm'%}") .then(response => { var modalHeader = response.data.header var modalData = … -
Return an image as a GET response django
I would like to return a .png image with Django. I know I can serve a basic HTML file in which I would have an <img src"">. I would like to be able to serve just the image just like in here: https://static.toiimg.com/photo/msid-67586673/67586673.jpg?3918697 I have an /images/ folder with this image and a Django Model class CatImage(django.db.models.Model): image = models.ImageField(upload_to="images/") Preferably, I would like to serve it with a GET response. -
Django - HTML input value not printing in Views
I want to pass an input value to views, assign variable, and print out the result. HTML: <div class="collapse navbar-collapse" id="navbarColor02"> <form class="col-sm-12" method="POST">{% csrf_token%} <div class="form-group row"> <input type="text" class="col-sm-10 form-control" name='stockList'> <div class="col-sm-2"> <button type="submit" class="btn btn-primary mb-2">Append</button> </div> </div> {% block label %}{% endblock %} </form> views: def home(request): print(request.POST) if request.method == 'POST' and request.POST: stockPost = request.POST.get('stockList','') print(stockPost) expected Result: when clicking submit, the terminal will display the values in 'stockList' Actual result: the terminal does not print the values in 'stockList' I saw some explanations regarding the queryDict but had a hard time following them. Any help would be greatly appreciated! -
Unrecognised error when deploying django app to heroku with git push
I have a django app with the following file structure - project_name (settings, __init__, urls, asgi, wsgi ... *.py) - manage.py - app_name - templates (template files) - static (just some static files) (urls, views, apps, models __init__ and the other usual files within django app *.py) - requirements.txt I think that I have run all the necessary commands inside top-level directory (containing project_name and app_name sub-directories) git init heroku git:remote -a (heroku_app_name) git add . git commit -am "this is a commit message" and then the error comes in git push heroku master with the following log: remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting django remote: Downloading Django-3.1.3-py3-none-any.whl (7.8 MB) remote: Collecting django-heroku remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting sqlparse>=0.2.2 remote: Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) remote: Collecting asgiref<4,>=3.2.10 remote: Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) remote: Collecting pytz remote: Downloading pytz-2020.4-py2.py3-none-any.whl (509 kB) remote: Collecting whitenoise remote: Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) remote: Collecting psycopg2 remote: Downloading psycopg2-2.8.6.tar.gz (383 kB) remote: Collecting dj-database-url>=0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Building wheels for collected packages: psycopg2 remote: Building … -
How to Sum time values from a specific month in Django?
I have the following view in my views.py: timesheet = Timesheet.objects.annotate( total_time=ExpressionWrapper( ExpressionWrapper(F('out') - F('entry'), output_field=IntegerField()) - Coalesce(ExpressionWrapper(F('lunch_end') - F('lunch'), output_field=IntegerField()), Value(0)), output_field=DurationField() ) ) This allows me to calculate the total worked hours in a single day, which is then looped on a table. But, I need to be able to Sum all the total worked hours from each specific month. Is this achievable? -
How to select a DateTime on a Django website using a selector filled with local JavaScript logic?
I am building a website using Django on the backend. On the website, there should be a form which allows a user to select a date and time. The exact date and time which users should be able to select depends on their current timezone. Therefore, I implement the logic showing users possible times with JavaScript on the users side. Currently, I was using a forms.DateTimeField but this gives me a textbox UI when using the {{ form.as_table }} in the template. I want to show the users a selector UI, so I manually implemented it in HTML and filled it with JavaScript. Now I ran into problem that the time format depends on local language of the user - for example, it is different in the German and the English language. So my question is, what should I do instead? I feel like my above solution has too much technical debt to pursue it further. Should I create a custom form field, and then just transmit the UNIX timestamp which I can easily convert back and forth using JavaScript on the users side? Or is there some other architecture / solution or even a already available code online? I … -
Angular + Django: runtime.js:1 Uncaught SyntaxError: Unexpected token '<' when rendering build index.html
I have a Django application, that I am attempting to pair with an Angular application. The angular application is inside the Django application, and the Django application is using the build directory, dist, for its templates. I have a simple view that uses the index.html inside the dist build folder: index = never_cache(TemplateView.as_view(template_name='index.html')). And a simple URL to send any unmatched urls to the index. re_path('.*', index, name="index") I tested this with ReactJS and I was able to start django and get the ReactJS project at localhost:8000, but with Angular, I get these errors. runtime.js:1 Uncaught SyntaxError: Unexpected token '<' polyfills.js:1 Uncaught SyntaxError: Unexpected token '<' styles.js:1 Uncaught SyntaxError: Unexpected token '<' vendor.js:1 Uncaught SyntaxError: Unexpected token '<' And inside my django terminal I can see: [09/Nov/2020 19:36:24] "GET / HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /runtime.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /vendor.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /main.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /styles.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /polyfills.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /favicon.ico HTTP/1.1" 200 752 Which is strange to me. How do i go about fixing this error, so my Django application can render the angular project? -
Django: Save auth_user to model with Foreign Key
The scenario is the following: I have a Django form which places a post request to the backend. With this data, I create an instance of my order model. One order can have one customer and a customer can have one auth_user. Database is SQLite. The relation looks like this: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT) class Customer(models.Model): email = models.CharField(max_length=MAX_TEXT_LENGTH) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) I managed to save all of them, order and customer are correctly related in the database. Although I am somehow failing while saving the user to customer. I save them like this in my view.py: with transaction.atomic(): # create customer & order customer = create_customer(first_name, last_name, email, phone) order = create_order(customer, form.cleaned_data) # add additional stuff to order order.additional_services.add(*form.cleaned_data['additional_service']), order.save # create user and update customer plain_user_password = generatePassword(DEFAULT_PASSWORD_LENGTH) user = create_user(order.id, email, plain_user_password, first_name, last_name) customer.user = user customer.save I create all my models with Model.objects.create(...) Using the order.id as username is a given and cannot be changed. The last two lines seem not to work, although the customer holds the correct user_id afterwards, the column in the database table is ... No exception occurring when I use a try-catch block either... What … -
<button type="button" onclick = "locations.href='{% url 'log' %}'">logout</button>
<html lang=“en“> <head> <meta charset=“UTF-8“> <title>Title</title> <style> div{ position : absolute; right : 10px; top : 5px } .button { display: block; width: 115px; height: 25px; background: #4E9CAF; padding: 10px; text-align: center; border-radius: 5px; color: white; font-weight: bold; line-height: 25px; } </style> </head> <body> <main> <div> <button type="button" onclick = "locations.href='{% url 'log' %}'">logout</button> <a class = "button" href = "{% url 'log' %}">LOGOUT</a> </div> </main> Welcome {{e}} code in the anchor tag is working as a logout button but not when I am using button, its showing error. The problem with the anchor tag is after clicking the logout login page is coming but I can go back to home page again without logging in. Please help me with this. -
I want to display categories from CATEGORIES_CHOICE but doesnt show anything
I'm creating simple website with navbar where i want to show categories from CHOICE tuple, but when i launch my website i cant see anything there. My models.py CATEGORY_CHOICE = { ('K','K1'), ('S','S1'), ('D','D1') } class Item(models.Model): ... category = models.CharField(choices=CATEGORY_CHOICE, max_length=1) ... views.py def item_categories(request): context = { 'header': 'Cakes', 'cakes': Item.objects.all(), 'categories': CATEGORY_CHOICE } return render(request, 'home.html', context) and my home page ... <div class="col-2"> {% for category in categories %} <a href="#"><h6>{{ category }}</h6></a> {% endfor %} </div> ... Any hints why it isn't showing me the categories? Many thanks! -
AttributeError: 'ServiceModel' object has no attribute 'service_id'
i'm new to programming in django. I have an error when I do manage.py runserver, the error occurs; AttributeError: 'ServiceModel' object has no attribute 'service_id'. I re-created my virtual environment and installed the requirements, but the same error occurs again. -
DJANGO CLASSE-BASE-VIEWS WORKING WITH PRIMARY KEY
AM TRYING TO CREATE A MULTI-USER PROJECT USING DJANGO AND CLASSE BASE VIEWS.....AM TRYING TO CREATE A BLOG WITH A BLOG_TITLE AND A BLOG_MESSAGE AS ARGUMENTS, I WAS SUCCESSFUL ON CREATING THE OBJECTS AND REDIRECTING TO ANOTHER PAGE, BUT NOW AM TRYING TO GET THE USERS NAME... here are my urls here are my calsse this is my template which is getting the title and the blog-message This are my models i was SUCCESSFUL on doing this using the django-admin section, but not able to do it in the code. -
Changes are not reflecting directly in Django admin page
In Django , I have a model named "Sample" class Sample(models.Model): Name = models.CharField(max_length = 250) Business_process = models.CharField(max_length = 250,editable=False) Sub_business_process = models.CharField(max_length = 250,editable=False) def save(self,*args,**kwargs): self.Business_process = self. Application.BP self.Sub_business_process = self. Application.SBP super(Sample,self).save(*args,**kwargs) while saving this model , this function gets the values of BP and SBP from Application table and stores it in Sample model fields. But whenever the BP and SBP field values gets changed in Application table , the changes are not reflecting directly in Sample model unless we save . (ie)currently, the values are getting reflected only when the Sample admin page gets saved. The expectation is the values of BP and SBP needs to reflect in Sample admin when the page gets opened. Any idea? Thanks in advance -
Waypoint.Infinite is not a constructor
Hi everbody i have a problem about django infinite scroll paginations. I cant solve it. home.html <div class="infinite-container"> {% for post_display in post_data %} <div class="card infinite-item"> <div class="card-body"> {{ post_display }} </div> </div> </div> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], handler: function(direction) { }, offset: 'bottom-in-view', onBeforePageLoad: function () { $('.spinner-border').show(); }, onAfterPageLoad: function () { $('.spinner-border').hide(); } }); view.py class HomeClassView(ListView): model = EssahDisplayModel paginate_by = 2 template_name = "authenticated/home.html" context_object_name = 'post_data' Bu i get this error on console: (index):458 Uncaught TypeError: Waypoint.Infinite is not a constructor at (index):458 it the line 458 start: var infinite = new Waypoint.Infinite({.... Someone knows it ? thans -
Creating Django Package and View Authentication
I am trying to package an App that I have created in a Django project and now I'm wondering how to handle authentication in this apps' views. Throughout the app I have used both class SomeView(LoginRequiredMixin,...): pass # for views or @login_required def someFunction(request): pass # for functions in my views.py, but I would like to make authentication optional for future use. How does one handle this? I considered stripping Mixin and decorators from views and then handle this functionality in urls.py. Is this a viable option and of course, how would this be handled better. Thank you for your time! -
Django Taggit show all tags all pages
I am using taggit in Django , when i add tag this tag show all my blog article , i want to show this only in this article where i add. can anyone fix ? i mean for example when i add tag 'Aries' it show in Aquarius article , Scorpio article and etc url.py urlpatterns = [ path('',Home,name= "Home"), path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'), path("openblog/",blog_list, name="blog_list"), path("openblog/<slug:slug>",blogDetail, name="blogDetail"), path('ads.text', read_file), path('tag/<slug:slug>', tagged, name="tagged"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def blog_list(request): articles = Blogmodel.objects.all().order_by('-id') paginator = Paginator(articles, 8) page = request.GET.get('page') posts = paginator.get_page(page) articles = paginator.get_page(page) args = {'articles':articles,'posts': posts } return render(request,'blog.html',args) def tagged(request, slug): query = Q(body__icontains=slug ) | Q(Title__icontains=slug ) articles = Blogmodel.objects.filter(query).order_by('-id') paginator = Paginator(articles, 8) page = request.GET.get('page') posts = paginator.get_page(page) articles = paginator.get_page(page) args = {'articles':articles,'posts': posts } return render(request,'blog.html',args) form.py from django import forms from .models import Blogmodel class BlogForm(forms.ModelForm): class Meta: model = Blogmodel fields = [ 'Title', 'body', 'slug', 'tags' ] Html <p>Common Tags: {% for mt in common_tags %} <a href="/tag/{{ mt }}" class="badge badge-success">{{mt}}</a> {% endfor %} -
How to filter datetime using datetime in django?
I have a Homework model that I want to filter based on the date(date_view) to show the homework. It looks like this- Homework model class Homework(models.Model): hw_id = models.CharField(unique=True, max_length=50) homework = models.TextField() subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) date_view = models.DateTimeField(default=datetime.now()) But when I try to filter like this- hw = Homework.objects.filter(class_id=class_id).filter(date_view__gte='homework__date_added') I get this error- ['“homework__date_added” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I think I am filtering the data in the wrong way. But how should I filter the data? -
URL patterns in django 3
I am really new to DJango and stuck at level 1. My problem is URL mapping. I am pasting the code here and let you know what I want to achieve. I have this file tree: enter image description here My myproj2 > urls.py has the following code from django.contrib import admin from django.urls import path, include from myproj2_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('help/', include('myproj2_app.urls')), ] And my myproj2 > myproj2_app > urls.py has the following code: from django.conf.urls import url from . import views urlpatterns = [ url('', views.index, name='index'), url('help/', views.help, name='help'), ] My myproj2 > myproj2_app > views.py has the following code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello This is my myproj2") def help(request): print("Getting to get help at least") help_dict = {'help_insert' : 'HELP PAGE '} return render(request, 'myproj2_app/help.html', context = help_dict) I have a folder 'templates' in my main myproj2 folder. In 'templates' folder, I have myproj2_app folder and then I have two html files. One is index.html and the other is help.html. I want to access http://127.0.0.1:8000/help/ where I am displaying simple text with {{ help_insert }} … -
Django Rest API relationship no such column
I want to get recipes from my django rest api but now I dont know how to get a recipe with the ingredients. I tried the following: My models.py: class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ForeignKey(Ingredients, related_name='ingredients', on_delete=models.CASCADE) class Meta: managed = False db_table = 'Recipes' My serializer.py: class IngredientsSerializer(serializers.ModelSerializer): class Meta: model = Ingredients fields = '__all__' class FullRecipeSerializer(serializers.ModelSerializer): ingredients = IngredientsSerializer(many=True, read_only=True) class Meta: model = Recipe fields = ['recipeid','title','images', 'preperation', 'ingredients'] And my view: class FullRecipesView(generics.ListCreateAPIView): serializer_class = FullRecipeSerializer permission_classes = [ permissions.AllowAny ] queryset = Recipe.objects.all() In the view, I am not sure if the queryset is right. But now I get the error: OperationalError at /api/full-recipes no such column: Recipes.ingredients_id And …