Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Second parameter in url being constructed with a dot (.) instead of /
I've got the following method in my View: @action(detail=True, methods=['delete']) def remove(self, request, *args,**kwargs): print("here") I've created a test for this endpoint. But haven't been able to get the correct url. When I do url = reverse('order-remove', kwargs={'pk':1234, 'product_id':1}) I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'order-remove' with a keyword arguments ... not found. 2 pattern(s) tried: ... and when I try: pk=1234 product_id=1 url = reverse('order-remove', args=(pk, product_id,)) I got the following url: /orders/1234/remove.1 instead of what I'd be expecting which is: orders/1234/remove/4 with an / instead of . What am I missing? -
How to update html form from two models form? The views don't works correctly with two models
Hear is my views.py which works with one models form and when I add some code for another >form, nothing add to db tables. It save only default data membership table. Html form fields looks like this {{ m_form.subscription_type }} MWhat else can be wrong? def add_user(request): view_all = User.objects.all() success = 0 current_user = request.user user = User.objects.get(username=current_user) m_user = Membership.objects.create(users=request.user) if request.method == 'POST': m_form = MembershipForm(request.POST, instance=m_user) form = AddUserForm(request.POST, instance=user) if form.is_valid() and m_form.is_valid(): temp = form.save(commit=False) temp.first_name = request.POST.get('first_name').capitalize() temp.last_name = request.POST.get('last_name').capitalize() temp.date_joined = parser.parse(request.POST.get('date_joined')) temp.save() m_form.users = form m_form.save() success = 'Successfully Added user' form = AddUserForm(initial={ 'username': request.user.username}, instance=request.user) user = User.objects.last() m_user = Membership.objects.last() context = { 'add_success': success, 'form': form, 'm_form': m_form, 'user': user, 'm_user': m_user, } return render(request, 'membership/add_user.html'.format(user.id), context) Hear is another file models.py class User(AbstractUser): birth_date = models.DateField(null=True, blank=True) height = models.DecimalField(max_digits=3, decimal_places=1, default=0) class Membership(models.Model): users = models.ForeignKey('User', on_delete=models.CASCADE, related_name="users") price = models.DecimalField(max_digits=5, decimal_places=2, default=0) subscription_type = models.CharField( ('Subscription Type'), max_length=30, choices=SUBSCRIPTION_TYPE_CHOICES, default=SUBSCRIPTION_TYPE_CHOICES[0][0] ) def __str__(self): return f"{self.first_name} - {self.last_name}" and forms.py class AddUserForm(ModelForm): def __init__(self, *args, **kwargs): super(AddUserForm, self).__init__(*args, **kwargs) self.fields['first_name'].error_messages = {'required': 'Please enter first name'} self.fields['last_name'].error_messages = {'required': 'Please enter last name'} self.fields['username'] class … -
type object 'HttpResponse' has no attribute 'User'
I am trying to create projects to currently signed in users. I've tried many different things with my CreateProjectView class however keep running into errors. My codes are below. Models.py models.py Views.py views.py error code AttributeError: type object 'HttpResponse' has no attribute 'User' [06/Mar/2021 11:55:09] "POST /add HTTP/1.1" 500 88813 -
Django with a Python API?
I have a python script that scrapes tweets off of Twitter and wanted to make it into a website. My script outputs a text file with the scraped tweets. I figured out how to render the contents of this text file onto my Django website but I don't know how to get the scraper to run every time someone refreshes the website so they get the latest tweets. Does anyone know how to make that work or point me in the right direction? I'm kind of a complete beginner when it comes to web development so I might not fully understand how this exactly works. -
how to use custom js in django inlineformset?
i have used Inlineformset in my django project , but i have to use my own js for increasing forms ! but i didnt find any way to make it work this is my models.py class Invoice(models.Model): seller = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='InvoiceItem') class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3) cash = models.DecimalField(max_digits=20,decimal_places=3) discount = models.DecimalField(max_digits=20,decimal_places=3) and this code is my views.py , i have used Class Based View class CreateClientInvoiceView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = CustomerInvoice form_class = ClientInvoiceForm template_name = 'invoiceapp/create_invoice.html' def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = CustomerInvoiceInlineFormset(self.request.POST) data['items'].full_clean() else: data['items'] = CustomerInvoiceInlineFormset() return data def form_valid(self, form): res = super().form_valid(form) self.object = form.save() context = self.get_context_data() items = context['items'] with transaction.atomic: form.instance.seller = self.request.user if form.is_valid() and items.is_valid() and items.cleaned_data !={}: items.instance = self.object items.save() form.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('invoiceapp:customer-invoice',kwargs={'pk':self.object.pk}) this is my html + js code {% extends 'base.html' %} {% load widget_tweaks %} {% load static %} {% block title %} create new invoice {% endblock %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice" style="direction: ltr !important;"> <div class="p-1 pr-2 … -
how to pass django params in react components
i am new to react , i am building simple blog where user can post with title and body in html its done with listview with: {% for x in object_list %} {% endfor %} but in react component its not getting good result and showing error here is my code: models class post(models.Model): title = models.CharField(max_length=100) body=models.TextField() views class list(ListView): model = post template_name = 'index.html' post.js function Post(){ return( {% for x in object_list %} {% endfor %} ) } in react what can i do to retreive data from model like we used to do in normal html, or show the object from model in components?? -
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...