Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add django_contrab schedules returns "Unknown command: 'crontab'"
I have configured django-crontab accordingly in my newly installed WSL2, ubuntu. And, when I did run python manage.py crontab add it worked just fine yesterday. Today, I tried to run the command again, and it returns: Unknown command: 'crontab' Type 'manage.py help' for usage CRONJOBS = [ ('*/5 * * * *', 'coreapp.cron.update_survey_summary') ] INSTALLED_APPS = [ "django_crontab", "drf_spectacular", "rest_framework", .... # coreapp.cron.update_survey_summary from coreapp.models import Event, User def update_survey_summary(): u = User.objects.get(id=6) e = Event( creator=u, title="Event ", location="Algeria", hosted_by="Admin" ) print("saving...") e.save() One other thing is that the django app would run successfully with python3 manage.py runserver. Which I find weird. -
Django DateInput widget format
I am trying to change the date format from mm/dd/yyyy to dd/mm/yyyy in a DateInput widget. I am trying to change the format the following way. class Meta: model = Patient fields = '__all__' widgets = { 'date_of_birth': widgets.DateInput( format='%d-%m-%Y', attrs={'type': 'date', 'class': 'form-control'}) } I noticed that if I don't include the 'type': 'date' attribute the date is interpreted in the correct format, but in that case the widget isn't displayed but just a text-field. So you have to write the date manually (including /). I have also tried changing the settings.py the following way which also didn't help. LANGUAGE_CODE = 'en-GB' TIME_ZONE = 'CET' USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = ('%d/%m/%Y') -
What is the best practice in handling multiple database aggregations and pagination
I have a REST service(the Project uses django and DRF) which serves data from a MSSQL database. One of the models stored inside the DB are invcoies which looks like this: class Invoice(models.Model): id = models.IntegerField(primary_key=True) customer = models.ForeignKey('project_models.Customer', on_delete=models.CASCADE,related_name='invoices') material = models.ForeignKey('project_models.Material', on_delete=models.SET_NULL) quantity = models.FloatField() revenue = models.FloatField() invoice_date = models.DateField() I want to expose some aggregated data for these invoices per material like: Sum of revenue for the current year Sum of revenue for the past year Sum of revenue for the past year up to todays date (e.g. today is 2022-03-02, Sum would be from 2021-01-01 to 2021-03-01) To solve this I could execute a query with minimal aggregation(e.g.revenue sum per day) and iterate over the result set to create a list of entries which contains all necessary informations. However as there are lots of materials this solution can lead to performance issues. This problem would normally be solved by paginating the queryset. Seeing as I still fetch and calculate as well as iterate over all the data of the DB it seems to be not the best solution. Therefore my question is: what would be a the best approach to aggregate multiple data while still … -
How to restrict cache data from google search in Django project?
i am built a django project and i used redis cache in my project but if i type in google search bar cache : my site domain name google listing all my cache json object data i don't have idea how it is there any way to restrict ? Thankyou in advance. -
Sum of two calculated annotation in django
.annotate( waste=Sum("processings__chunks__waste"), completed_waste=models.Task.get_completed_waste_annotation(), tooling_time=Sum("processings__chunks__tooling_time"), completed_tooling_time=models.Task.get_completed_tooling_time_annotation(), processing_time=Sum("processings__chunks__processing_time"), completed_processing_time=models.Task.get_completed_processing_time_annotation(), total_time=F("tooling_time") + F("processing_time"), completed_total_time=F("completed_tooling_time") + F("completed_processing_time"), ) I've this annotate, the problem is in the last two fields total_time and completed_total_time, when one of the fields tooling_time, processing_time is None, I get None in both of the fields. -
How to show user's information (special ID, firstName, lastname) in another template after successfully form submission in Django
How to show user's information (special ID, firstName, lastname) in another template after successfully form submission in Django. I have a form to ask users information(general information, Education, experience) and I give random unique test_id. After user submitted form succesfully, I have to show his/her test_id to memorize. I didn't have an idea about view form. My solution is a bit stupid My model: class UserForm_uz(models.Model): test_id = models.CharField(default=random_string,max_length=5,editable=False,unique=True) rasm = models.ImageField(upload_to='media/rasmlar',null=True,blank=True) jobName = models.ForeignKey( Job, on_delete=models.CASCADE ) lastName = models.CharField(max_length=200) firstName = models.CharField(max_length=200) middleName = models.CharField(max_length=200,blank=True,null=True) birthData = models.DateField() nation = models.CharField(max_length=50,blank=True,null=True) My view: class FormAfterView(View): def get(self,request): obj = UserForm_uz.objects.all().last() test_id = obj.test_id firstName = obj.firstName lastName = obj.lastName return render(request,"formafter.html",{"test_id":test_id,"firstName":firstName,"lastName":lastName}) -
djagngo get all .objects.filter() with condtion
I Have a table Batch with many columns Column Type Comment id bigint(20) Auto Increment start_date datetime(6) NULL acerage double batch_health int(11) NULL stage varchar(100) NULL expected_delivery_date datetime(6) NULL current_pdd double NULL historic_pdd double NULL current_gdd double NULL historic_gdd double NULL sub_farmer_id int(10) unsigned NULL batch_status varchar(100) commodity_id int(10) unsigned NULL commodity_variety_id int(10) unsigned NULL farm_id bigint(20) NULL created_at datetime(6) created_by_id int(10) unsigned NULL updated_at datetime(6) updated_by_id int(10) unsigned NULL actual_produce double NULL actual_yield_per_acre double NULL expected_produce double NULL historical_yield_per_acre double NULL sop_adherence double NULL end_date datetime(6) NULL batch_median_health int(10) unsigned NULL batch_name varchar(200) NULL commodity_name varchar(200) NULL pending_tasks int(10) unsigned NULL pest_attack varchar(500) NULL when I trying to get the object from this table like this Batch.objects.filter(farm_id = farm_id, batch_status='completed') farm_id variable is already defined then I should all the data column for that Batch But I am not getting ALL all columns I am getting an only batch name as an output (2706) Papaya | 2021-03-18 (2707) Papaya | 2021-03-18 How can I get all the columns in dict ?? and so that I can use this in the filter of batchyield batch_id Is a foreign key in batchyield which is batch table ID and get batchyield all … -
how can I check that societies name contain city or locality name and update the society name?
I have data of societies in my database but there are some societies that contain city names and locality names. I want to check whether the society name contains the city name and locality name and remove them or update the society name. models\locality.py class Society(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. locality = models.ForeignKey('Locality', models.DO_NOTHING, db_column='localityId', blank=True, null=True, related_name='society_set') # Field name made lowercase. dot_com_database_id = models.IntegerField(db_column='dotComDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'societies' models\society.py class Locality(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. city = models.ForeignKey('City', models.DO_NOTHING, db_column='cityId', blank=True, null=True, related_name='locality_set') # Field name made lowercase. connect_database_id = models.IntegerField(db_column='connectDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'localities' It will clear your doubts: Iterate through societies that do have names and for each society. If the issue of appending city & locality exists for the society. Remove city name & locality name from society's name and update society name. e.g. Society … -
ImportError at libGL.so.1: cannot open shared object file: No such file or directory
I was using python-poppler 0.2.2 in a django project. It worked in Local Server but when it is hosted in Azure Linux based app service, it is getting a error like ImportError at libGL.so.1: cannot open shared object file: No such file or directory Tried installing apt install libgl1-mesa-glx, sudo apt-get install python3-opencv -
Render formset in template django and create table
How to create this table used modelformset_factory Table: In view I create standard formset: def studentTeacherFees(request, *args, **kwargs): ... FeeFormSet = modelformset_factory(Fee, fields=('is_paid',), extra=0) ... In template 'my_template.html' i try used this: ... <form class="form validate-form" id="Career" method="POST" enctype="multipart/form-data"> <span class="form-title"> {% translate "Info" %} </span> {% csrf_token %} <legend class="border-bottom mb-4">{% translate "Update Info" %}</legend> <ul> {{ formset.management_form }} {% for form in formset %} {{ form.id }} <li> {{ form.instance.student.get_full_name }} {{ form.is_paid }}</li> <br> {% endfor %} ... -
How to test uploadfile in django
I have an uploadform and I want to test it. But there is a problem. def test_if_can_upload_file(self): with open('app_blog/tests/test.txt') as file: self.client.post(reverse('csv_blog'), {'attachment': file}) test_file = file.read() self.assertEqual(test_file, 'test file') When I test it, there is an error: self.assertEqual(test_file, 'test file') AssertionError: '' != 'test file' + test file Why is my file shown like it is empty? Actually it is not empty.Or maybe I test my form in a wrong way? form class UploadBlogForm(forms.ModelForm): file = forms.FileField() class Meta: model = Blog fields = 'file', view def upload_blog(request): if request.method == "POST": upload_file_form = UploadBlogForm(request.POST, request.FILES) if upload_file_form.is_valid(): blog_file = upload_file_form.cleaned_data['file'].read() blog_str = blog_file.decode('utf-8').split('\n') csv_reader = reader(blog_str, delimiter=":::", quotechar='"') -
Error opening files with Diacritic letters
I use {% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}">{{i.file.name}}</a></p>{% endfor %} To open attached files to my post. Problem is, when I try to open PN/pravokutne_pločice.jpg I get error: “C:\inetpub\media\PN\pravokutne_plo” does not exist Raised by: django.views.static.serve I figured out it's because of diacritic letters. On my 'base.html' I have . Django setting 'LANGUAGE_CODE = 'hr-BA''. Is there something I can add to be able to open those files which names contain diacritic letters? -
Django static files are broken
I'm trying to add a background picture to the hero section in Django, But whenever I open that URL: http://127.0.0.1:8000/static/img/bg.png it says 'img\bg.png' could not be found I also attempted to open other urls, but they are broken. #settings STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = 'E:\coding\django\pawnhost\static' #urls from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include("core.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #html <section class="Hero"> ... </section> #CSS (base.html) {% load static %} <style> .Hero { background-image: url({% static 'img/bg.png' %}); } </style> -
Flitering django queryset based on ManyToManyField
In my Request model, there is a field requested_to which is a ManyToManyField requested_to = models.ManyToManyField(OrganizationUser) I want to filter queryset of Request model where a organization_user is not in requested_to -
DJango Query Issue
I am making a Blog website where my blog post model is related to User model using many-to-many relation for the likes. Now I am querying the DB for getting the likes count for each specific post. This is the Query that I have written -> posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now When I see the actual Query that is being made to the DB and the result It all looks fine and the No of queries are also made to DB are fine. I am getting a column named 'LIKES__COUNT'. Now I am unable to use this column name in my template. Can anyone help me out on how to use this in the template? This is the result That I am getting from the DB. -
How to switch wagtail homepage depending on user logged in status
I have previously been using path("", include(wagtail_urls)) for my home_page url which displays the template at home/home_page.html correctly I wish to however display different pages depending on whether a user is logged in or not so have changed this to: def logged_in_switch_view(logged_in_view, logged_out_view): '''switches views dependedn on logon status''' def inner_view(request, *args, **kwargs): if request.user.is_authenticated: return logged_in_view(request, *args, **kwargs) return logged_out_view(request, *args, **kwargs) return inner_view urlpatterns = [ path("", logged_in_switch_view( TemplateView.as_view(template_name="home/home_page.html")), TemplateView.as_view(template_name="home/not_authenticated.html")), name="home"), ] With this approach (directly specifying the template rather than using wagtail_urls) the home page does not display correctly when logged in, in that all the wagtail tags in the html e.g. the blog posts are not displaying home_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block content %} <main class="container"> {% for post in page.blogs %} {% with post=post.specific %} <div class="col-md-8 mx-auto px-auto"> <div class="row border rounded overflow-auto flex-md-row mb-4 shadow-sm position-relative "> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong> <div class="mb-1 text-muted">{{ post.date }}</div> <h3 class="mb-0">{{ post.title }}</h3> <p>{{post.intro}}</p> </div> <div class="col-auto my-auto py-2 px-2 d-none d-lg-block"> <a href="{% pageurl post %}" class="stretched-link"> {% with post.main_image as main_image %}{% if main_image %} {% image main_image min-250x250 … -
How to raise custom validation error for a serializer field?
class SomeSerializer(serializers.ModelSerializer): first_name = serializers.CharField(validators=[RegexValidator( regex=(r"^[a-zA-Z_ \- \. \' ]+$"), message="Enter a valid first name")]) phone = serializers.IntegerField(source="user.phone") Now, this phone field since called an integer field, is giving a validation error, "Enter valid integer". How can I make that a custom message? -
Django All Columns Are Distinc
Given that I have a data. id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 4, Bibble Way, Leicester 5, High Street, Londidium 6, High Street, Londidium I want to distinct so that it would only delete Bibble Way, Leicester and High Street, Londidium because it is the only entry where all columns have a duplicate. I already tried .distinct('street','city') but it deletes if either street or city has a duplicate. I want to only delete if all columns match. Whats the right query to get result of id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 5, High Street, Londidium -
What would cause the same Django template include block to behave differently twice on the same page?
I'm including a simple pagination template into a template that lists blog posts. It gets output without getting interpreted, as in, I see the double curly brace enclosed tag as text in the resultant webpage. But, when debugging, I pasted same block higher in the page, and it gets interpreted fine. Between the two, I iterate over the same object that gets passed to the pagination template, so this is probably something that I don't understand about the state of that object? Or Django's rendering process. {% extends "blog/base.html" %} {% block title %}My blog site thing{% endblock %} {% block content %} <h1>Blog site</h1> **{% include 'pagination.html' with page_object=posts %}** {% for post in posts %} <h2><a href="{{post.get_absolute_url}}">{{ post.title }}</a></h2> <p class="date">Published {{post.publish}} by {{post.author}}</p> {{post.body|truncatewords:5|linebreaks}} {% endfor %} **{% include 'pagination.html' with page_object=posts %}** {% endblock %} Pagination.html <div class="pagination"> <span class="step-links"> {% if page_object.has_previous %} <a href="?page={{ page_object.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_object.number }} of {{ page_object.paginator.num_pages }}. </span> {% if page_object.has_next %} <a href="?page={{ page_object.next_page_number }}">Next</a> {% endif %} </span> </div> views.py for this app from django.shortcuts import render, get_object_or_404 from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request): … -
Need to link the Loggin User with the User model created by me in django framework
User Model class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneNumberField() emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return self.employee_name serializers class UserSerializers(serializers.ModelSerializer): #Email Notification def create(self, validate_data): subject = 'Your account was activated' plain_message = 'SAMPLE TEXT' from_email = 'demomaster147@gmail.com' to_email = validate_data['email'] EmailThread(subject, plain_message, from_email, to_email).start() return User.objects.create(**validate_data) dob=DateField(input_formats=DATE_INPUT_FORMATS) class Meta: model= User fields ='__all__' password = serializers.CharField(max_length=128, write_only=True, required=True) admin class StaffAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) #job = qs.filter(job_name='test job').first() #print(f"\nQUERY : {job}\n") #print(f"\nQUERY USER : {job.user}\n") print(f"\nrequest.user : {request.user}\n") if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id) #Admin SuperUser @admin.register(User) class UserAdmin(ImportExportModelAdmin): list_display = ('id','employee_name','email','billable_and_non_billable','designation') search_fields = ['employee_name'] pass Actually with the above code I couldn't able to get the details of logged in user details or user inputted data alone. I have a User model created to add the details of the user in my project and that is not connected with the logged in user. for example (if i register a user as "vinoth" with username and email, and i entered a user with the same details … -
I create a One to One realtionship in django Multitable-Inheritance but it not show Book-id in my child class Table and also show Integrity Error Why?
This is my models.py : class Book(models.Model): Book_Name = models.CharField(max_length=100, default="Don Quixote") Author_Name = models.CharField(max_length=100, blank=True, default="Miguel de Cervantes") Price = models.FloatField(default=175.00) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.Book_Name class ISBN(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE, parent_link=True, primary_key=True) Isbn = models.CharField(max_length=100) def __str__(self): return self.Book_Name in according to my code every Book has one isbn number but in admin panel ISBN table don't show book attributes or don't show any book-id. it show only Isbn column and after i give input in this column it show me error "IntegrityError at /admin/inheritance/isbn/add/" and "NOT NULL constraint failed: inheritance_isbn.book_id" This is my admin.py : @admin.register(Book) class PostAdmin(admin.ModelAdmin): list_display = ['Book_Name', 'Author_Name', 'Price'] @admin.register(ISBN) class PostAdmin(admin.ModelAdmin): list_display = ['book', 'Isbn'] I'm a noob to python and Django so any help would be greatly appreciated. -
Does live travel tracking of user possible in django website
I am working on Django website and I want to implement user live travel tracking.Is it possible to implement live tracking of user in the Django website.If Yes, How it is possible. -
Plotly chart not showing in django web app
I've been trying to do this for hours and I still can't figure it out. This is my code for the plot in 'functions.py' def candles(): symbol = 'AAPL' stock = yfinance.Ticker(symbol) hist = stock.history(period='1y', interval='1d') figure = go.Figure(data = [go.Candlestick(x =hist.index, open = hist['Open'], high = hist['High'], low = hist['Low'], close = hist['Close'])]) x_axis = figure.update_xaxes( title_text = 'Date', rangeslider_visible = True, rangeselector = dict( buttons = list([ dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'), dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'), dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'), dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'), dict(step = 'all')]))) layout = figure.update_layout( title = { 'text': 'AAPL', 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) y_axis = figure.update_yaxes( title_text = 'AAPL Close Price', tickprefix = '$') chart = plot(figure, x_axis, layout, y_axis, output_type = 'div') return chart My 'views.py' def chartView(request): candlestick = candles() context={ 'candlestick' : candlestick } return render(request, 'portfolio.html', context) In portfolio.html I'm using {{candlestick | safe}} -
why is the url in django not reading the primary key and just reading it like a string?
def lead_update(request,pk) : lead = Lead.objects.get(id=pk) form = LeadForm() if request.method == "POST" : form = LeadForm(request.POST) if form.is_valid() : first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] age = form.cleaned_data['age'] lead.first_name = first_name lead.last_name = last_name lead.age = age lead.save() return redirect("/leads/{{ lead.pk }}/") # the problem context = { "form" : form, "lead" : lead } return render(request,"leads/lead_update.html",context) on debug : it is showing The current path, leads/{{ lead.pk }}/, didn't match any of these. -
How to refresh image with new random one from list in Django
I have a working function that loads a random image from a collection of images in firebase and displays it in template. However the image doesn't seem to reload on page refresh and that is exactly what I want. How can I achieve this? Working Function. def fetchsliderimages(): big_list = [] ref = dbs.reference('cartoons/sliderimages') snapshot = ref.order_by_child("timestamp").limit_to_last(100).get() if snapshot: for value in snapshot.values(): big_list.append(value['image']) image = random.choice(big_list) return image How I Load The Image <img width="100%" height="110%" src="{{ summary.sliderimages }}">