Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use sorl-thumbnail package together with django-tables2 package?
I do have a table defined in tables.py that renders a column with recipes images. class ImageColumn(Column): def render(self, value): return format_html( '<img src="static/media/{url}" height="150px", width="150px">', url=value ) class RecipeTable(tables.Table): image = ImageColumn() name = Column(linkify=True) class Meta: model = Recipe template_name = "django_tables2/bootstrap4.html" fields = ( "image", "name", "directions", "ingredients", ) Each image has different size and when I render it with fixed height="150px", width="150px", aspect ratio messes up the image. Therefore I thought I could use sorl-thumbnail package to help mi with generating thumbnails, rather then resizing the whole images. It looks like it is not possible to easily use both django-tables2 and sorl-thumbnail since thumbnails are rendered in html template. My template contains only this to render the table: {% render_table table 'django_tables2/bootstrap4.html' %} I need to access the cell so that I can use thumbnail template tag where image should be placed. {% thumbnail item.image ‘200x100’ as im %} <img src=’{{ im.url }}’> {% endthumbnail %} The only solution I see could be to edit the bootstrap4.html, but is there a better way? Am I missing something? -
How Can I get and change M2M Inline elements field on Inline level
I have two Models. I've added Lectures as Tabularinline to Classroom. At admin panel I want to change their ordering at classroom admin page. Is there any way to add custom fields to TabularInline and edit this field ? class Lecture(models.Model): title = models.CharField(max_length=200) link_name = models.SlugField(max_length=250, unique=True) subtitle = models.CharField(max_length=200, blank=True, null=True) order = models.IntegerField(default=0) modules = models.ManyToManyField(Module, blank=True) class Meta: verbose_name = "Lecture" verbose_name_plural = "Lectures" def __str__(self): return self.title class Classroom(models.Model): owner = models.ForeignKey(Member, on_delete=models.PROTECT, blank=True, null=True) title = models.CharField(max_length=200) link_name = models.SlugField(max_length=250, unique=True) subtitle = models.CharField(max_length=200, blank=True, null=True) definition = RichTextField(blank=True, null=True) order = models.IntegerField(default=0) lectures = models.ManyToManyField(Lecture, blank=True) class Meta: verbose_name = "Classroom" verbose_name_plural = "Classrooms" def __str__(self): return self.title -
im getting error in django Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about/
code of project named carparts urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('parts.urls')), ] code for my app named parts urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index,name='index'), path('about', views.about,name='about'), path('contact', views.contact,name='contact'), ] code for views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'index.html') # return HttpResponse('this is home page') def about(request): return render(request, 'about.html') def contact(request): return render(request, 'contact.html') both about and contact page is error but index is correct . Can any one help me with this code Thank you -
How to embed a video stream using django httpstreamingresponse
I am running django on a raspberry pi to serve a webcam stream. Currently my view is simple and looks like: class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def videoStream(request) return StreamingHttpResponse(gen(VideoCamera())), content_type="multippart/x-mixed-replace;boundary=frame") When I access this view directly in chrome (http://127.0.0.1:8000/videostream), the video feed shows up and works as expected. But what I want is to embed this stream on a separate page. My thought was that I could just do: <video src="http://127.0.0.1:8000/videostream" autoplay="autoplay" > or <img src="http://127.0.0.1:8000/videostream" Both will make the request to the view, but the stream won't start. I suppose I just don't understand how the browser knows what to do when I directly access http://127.0.0.1:8000/videostream. It just works...I don't understand why.. -
DJANGO FORMS VALIDATION
There are different ways of validation in Django forms like clean(), is_valid() and validators. I want to know When to use which method and the difference among them ? -
Trying to deploy django app to heroku and having an issue with collect static storage.py path
I am trying to deploy a django project to heroku and having a hard time with the static files. I have everything set up properly as it has worked for me in the past. I'm not sure what the issue is this time. Below is my traceback. It seems to be something with the static files path but it shouldnt have a problem if I have my STATIC ROOT and URL correct right? -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 109, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_0728dd1c_/static' Please help. I know the Static File deployment with heroku … -
django add or update datas in database
I would like to create a form with some features : if GTIN isn't already used -> create a new product in my database else if GTIN already used -> update dateExpiry corresponding to this GTIN in my database my code is the following one: // form.py class productForm(ModelForm): class Meta: model = Product fields = ['GTIN', 'name', 'price', 'expiryDate'] //views.py def index(request): if request.method == "POST": form = productForm(request.POST).save() return redirect('/cbPlus') else : form = productForm() template = loader.get_template('cbPlus/index.html') product = Product.objects.order_by('expiryDate') context = { 'product' : product, 'form' : form } return HttpResponse(template.render(context, request=request)) //models.py class Product(models.Model): GTIN = models.BigIntegerField(unique=True) name = models.CharField(max_length=25) price = models.FloatField(max_length=25) expiryDate = models.DateTimeField(max_length=25) -
Multiple detail pages according to relations
I have many to many related models. Type and Country. class Type(models.Model): name = models.CharField(max_length=100) class Country(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(blank=True, unique=True) types = models.ManyToManyField("Type", related_name="countries") def get_absolute_url(self): return reverse('country', kwargs={'slug':self.slug}) I will have a list of the countries related to types. I want to create separate detail pages for each type. Also, I need to have an actual detail page of countries. For example; Appetizer in France, ------------->(Template I) Soup and Salad in France --------->(Template I) Dessert in France ---------------->(Template I) And France ----------------------->(Template II) I am sharing the design with you to visualize what I have. enter image description here How can I achieve this and which structure I need to build? I’m waiting for your ideas and help. Thanks. -
npm run build takes to long in django+react app
recently i moved to react and i am quite familiar with it , now i started using react with backend django, after i set up it was all working but ,every time i change code and i want to see it , i need to npm run build , although this works but on real world projects where maybe 100s of js file , run build is gonna take hours to build , and i cant wait that long to do changes and it is very impractical.like python manage.py runserver makes instant easy updation , can you give me solution for this... -
How to use signals to make changes to other models
I have two models in my project, The LoanApplication and OnlineLoanPayment model. I would like to implement a feature where whenever someone makes a payment in OnlineLoanPayment,I want a the loanarrers field to be decremented by the amount paid using djnago signals. Below are my models and signals file. class OnlineLoanPayment (models.Model): Amount = models.FloatField(default=0,null=True,blank=True) ReceiptNumber = models.CharField(max_length=200,null=True,blank=True) PhoneNumber = models.CharField(max_length=200,null=True,blank=True) TransactionDate = models.DateTimeField(null=True,blank=True) Here is the LoanApplication model class LoanApplication(models.Model): load_id = models.CharField(max_length=25,blank=True,null=True) amountApplied = models.FloatField(null=True,blank=True) models.DateTimeField(null=True,blank=True,auto_now_add=True) interest = models.FloatField(null=True,blank=True) repayamentDuedate = models.DateTimeField(null=True,blank=True) loanArears = models.FloatField(null=True,blank=True) totalRepaymentAmount = models.FloatField(null=True,blank=True) is_cleared = models.BooleanField(default=False) def save(self, *args, **kwargs): loanApprovalDate = date.today() if not self.load_id: self.load_id = str(uuid.uuid4()).replace("-","").upper()[:5] if self.repayamentDuedate is None: self.repayamentDuedate = loanApprovalDate + datetime.timedelta(self.repayment_duration) if self.interest is None: self.interest = self.amountApplied / 100 * self.interestRate if not self.totalRepaymentAmount: self.totalRepaymentAmount = self.amountApplied + self.interest if self.loanArears is None: self.loanArears = self.totalRepaymentAmount if self.loanArears == 0: self.is_cleared = True return super(LoanApplication,self).save(*args, **kwargs) class Meta: verbose_name = ("Loan Application") verbose_name_plural = ("Loan Applications") from .models import * from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from mpesa.models import OlineLoanRepayment @receiver(post_save,sender=OlineLoanRepayment) def post_save_update_arears(sender,instance,created,**kwargs): if created: amount = OlineLoanRepayment.objects.all() for item in amount: print(item.Amount) # decrement the loanares field in … -
Django- site won't work unless the SECRET_KEY is hardcoded in SETTINGS.PY
I changed my django project's settings.py to load the SECRET_KEY as an environment variable: SECRET_KEY = os.environ['SECRET_KEY'] Then I stored my variable in /etc/bash.bashrc I set DEBUG=False, then restarted gunicorn,restarted nginx and rebooted the server. But my site stopped working (502 Bad Gateway) ! What exactly can be the problem here? I searched but I didn't quite get what might be the issue. BTW the site have been working fine before this change. -
Value not printed in checkbox when retrieving value using Django and MSSQL
i have a code that should retrieve the content to checkbox using the value from other dropdowns . so currently am able to get value of dropdown but not checkbox . i checked the name of column and all related things but everything is same as in db table . and was not able to find the reason why it is not working . index.html <br>&emsp;<label for="sn">Server Names:</label> {% for n in result5 %} <input type="checkbox" id="Server1" name="Server1" value="{{n.servername}}"> <label for="Server1"> {{n.servername}}</label>&emsp;&emsp; {% endfor %} models.py class Index(models.Model): # name = models.CharField(max_length=100) invid = models.IntegerField(primary_key=True) apptypeofpg1 = models.CharField(max_length=100) customerofpg1 = models.CharField(max_length=100) #TemplateName = models.CharField(max_length=100) environmentofpg3 = models.CharField(max_length=20) patchconfigofpg3 = models.CharField(max_length=100) views.py if request.method == 'POST': if request.POST['ServerDetails']: print("Hi") cursor5 = conn.cursor() cursor5.execute("select distinct(servername) from PatchingUI.dbo.mainDetails WHERE abc= '"+abc+"' and qwe ='"+qwe+"' and chs= '"+chs+"'; ") result5 = cursor5.fetchall() print(result5) but i am able to print contents in views.py . it shows the result of the query in views.py . But not in Html page . Not able to understand what is the reason why . -
Aggregate in django with decimal field
I applied aggregate sum on an integer field and it is returning as expected. But, when I apply it on decimal field it is returning 0. My model: class Sales (models.Model): price = models.DecimalField(max_digits=10, decimal_places=3, default=None) quantity = models.IntegerField(default=0) My query: sales_stats = Sales.objects.all().aggregate(Sum('price')) When I print the sales_stats it returns 0: {'price__sum': Decimal('0')} NOTE: there are values in price that are greater than 0. Is there something I'm missing here? -
Visualizing daily and weekly recording times in Django
I'm building an app for recording work hours in Django, and I'd like to be able to visualize the data by graphing the daily and weekly records together, but how do I create data to display in a line graph like the one below? Backend:Django Frontend:React Chart:ApexCharts.js Django / model class Entry(models.Model): project = models.ForeignKey(Project, related_name='entries', on_delete=models.CASCADE) time = models.IntegerField(default=0) user = models.ForeignKey(User, related_name='entries', on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return '%s - %s' % (self.project.name, self.created_at) I was able to get the daily data by using the following method, but how can I display the data for days with no records (days with zero records)? def get_report(self, obj): data = Entry.objects.all().values( 'created_at__year', 'created_at__month', 'created_at__day').annotate( Sum('time')).order_by('created_at__year', 'created_at__month', 'created_at__day') return data currently "report": [ { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 18, "time__sum": 1221 }, { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 22, "time__sum": 1201 }, ], Ideal shape(Display 0 even when there is no record.) "report": [ { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 18, "time__sum": 1221 }, { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 19, "time__sum": 0 }, { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 20, "time__sum": 0 }, { "created_at__year": 2021, "created_at__month": 2, "created_at__day": 21, "time__sum": 0 }, { "created_at__year": 2021, "created_at__month": 2, … -
How to make a serializer for multiple users (student & teacher)?
Hello I am very new to Django Rest Framework and I am having a hard time with the serializer. I extended the User Model using Abstract User. I inserted two new fields which are is_student and is_teacher then I set both of the values to false as default. I then put them in there own model then just applied a one-to-one relation for each of them to the user model. My problem is with the serializer. How do I make a serializer out of this. I want the student and teacher have relation with the user model as well as having the ability to do http actions such as get, post, put, etc. from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Course(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() def __str__(self): return self.user.username class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) age = models.IntegerField() address = models.CharField(max_length=200) def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) description = models.TextField() course_teaching = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(Student) def __str__(self): return self.user.username -
django html page can't load static files
I have a problem when I try to enter my website (zabarjad.co) and I've been trying to fix it for around 3 weeks now and still can't find any solution for it! I search about it here and youtube and google but there's no any help :( the issue is that it shows me the html file codes and not loading the Static files and I don't know what exactly the problem... I hope you enter the link above and see why It loading like this... or see this screenshot I use google compute engine with apache2 server and django web application thanks in advance -
Integrating Wagtail pages into existing Django project
I build a website using Django and I need to add functionality to edit every peace of every page blocks on a site. I found Wagtail and read the docs about how to integrate it and thought of the way to integrate it via django views, like this: main/pages.py: ... class IndexPage(Page): header_title = models.CharField(...) header_subtitle = models.CharField(...) ... main/views.py: ... def view_index(request): pages = Page.objects.all() page = pages.filter(...) # somehow filter index page return render( request, 'index.html', context={'page': page.specific}, content_type='text/html') ... Is it good way to use Wagtail pages and integrate it into existing Django views? Could any surprises be found along the way? -
AWS Elastic Beanstalk configure the allowed hosts for Django Application
I deployed a Django application into AWS Elastic Beanstalk. I mapped the DNS (external service) for my host to the AWS-EB CNAME. Everything works fine. I also enabled Django logs to send an email in case of errors and I notiest that I'm receiving also a lot of email like: "Invalid HTTP_HOST header: 'xxx.xxx'" For me it's not clear if I need to change something into Elastic Beanstalk configuration file (configuring only the allowed hosts) or if it's possible to block not allowed hosts at load balancer level. Some examples are welcome. -
Interactive Customizable Map for Websites
I need to have an interactive map on my website (html) on which geographical markers/points can be added based on user input from those who use the website. (For example the website user should be able to make a new entry in the map which would appear as a location marker.) Any suggestions on how I can achieve this task would awesome... -
Modify Djangos model-table outside Django
I have a model my_users with fields id,fruit, notified, time. The field notified and time are to be updated (preferably) on another machine than my Django App is running, due to it being a hefty computation. I can do it by e.g df = my_heavy_function() df.to_sql(my_app_my_users) but I'm afraid of writing issues/overlap if some user e.g edits his fruits while the to_sql function is writing (the DB is a PostgreSQL). Is it safe to use this approach, or what is the better way to do these kinds of update to Djangos models that is not a view as such but more a backend operation? -
Django runserver_plus restart immediately after running the server
I tried to set up a Django server with a self-signed SSL using the following command: python manage.py runserver_plus --cert /tmp/cert 0.0.0.0:8060 after running the server, it automatically restarts the server and loads all modules again and I can not find the reason. My output is like this: * Running on https://0.0.0.0:8060/ (Press CTRL+C to quit) * Restarting with stat Performing system checks... System check identified no issues (0 silenced). Django version 3.1.4, using settings 'rokhban.settings' Development server is running at https://0.0.0.0:8060/ Using the Werkzeug debugger (http://werkzeug.pocoo.org/) Quit the server with CONTROL-C. * Debugger is active! * Debugger PIN: 233-701-884 PS: No such thing happens when running the server with python manage.py runserver 0.0.0.0:8060 Why does this happen? -
django project sheme in form of tree in git bash
I'm creating my first django app and I want to ask what command in git bash can show structure of my project in form like at the underneath. Thanks for help │ ├───staticfiles └───webadvisorapi │ settings.py │ urls.py │ wsgi.py │ __init__.py │ ├───static │ .keep -
im trying to count model object but its not working
I'm trying to count model object using Django but it's not working, it doesn't display anything, that's the HTML code, I've tried both .all.count and .count but both aren't showing anything <div class="card"> <div> <h3>Followers: {{profiles.follower.all.count}}</h3> </div> <div> <h3>Followings: {{profiles.following.count}}</h3> </div> </div> And that's the python profile function code def profile(request, username): user = get_object_or_404(User, username=username) user_posts= post.objects.filter(user=user) profiles = Userprofile.objects.filter(user=user) context = { 'user_posts':user_posts, 'profiles': profiles } return render(request, "network/profile.html", context) The Model related class Userprofile(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='profile') follower = models.ManyToManyField('User', blank=True, related_name='follower') following = models.ManyToManyField('User', blank=True, related_name='following') -
How to use Django admin to create celery like tasks
I have a Django backend that I've created for a real estate company. I've built quite a few tasks that are hard coded and I'm wanting to make those tasks customizable via the admin page... but I can't quite figure out how to do that. For example, let's say that (from the admin) I wanted to make it possible to create a task that would send a custom message that would trigger based on a list of triggers (e.g. close date, client birth date, etc). Is this doable? This question is a little vague because I can't quite figure out how to ask what I'm wanting to do. I'm sure that there is a keyword(s) that I can type in to point me on the right path, but I have come up blank up to this point -
Django widget tweaks - date field is empty when using generic update view class
I have problem with generic update View - to customization of template i'm using widget tweaks when i'm trying to update date field with bootstrap class='form=control' my date field is empty. Despite in html value is filled correctly. All the time when i'm using update views my date fields becoms empty. <div class='col-6'> {{ form.data_przegladu.label }} {% render_field form.data_przegladu class="form-control" type='date' %} {{ form.tachograf.label }} {% render_field form.tachograf class="form-control" %} {{ form.data_legalizacji.label }} {% render_field form.data_legalizacji class="form-control" type='date' %} {{ form.uwagi.label }} {% render_field form.uwagi class="form-control" %} </div> Printscreen from my browser