Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webfaction Alternative
Will Heroku work for a website that has these features? We're looking for a web host with the following features—ideally a large, stable company (been around at least 5 years)—one that charges a reasonable monthly fee for the following: Latest versions of Django and Python Has inexpensive tier of hosting appropriate for a low-traffic Django site—on a typical day there may be a handful of users (perhaps between 5 and 50?), doing low-bandwidth activities (e.g. filling out text forms) Nginx or similar service to handle static files Postgres database (ideally with user-friendly database-management software for Postgres databases) Supports having multiple working versions (development, release candidate, and production) running at the same time, using different subdomains Supports wkhtmltopdf (to convert webpages to downloadable PDF files) Supports ability to send individual emails from Django -
Django field values are not getting autopopulated in TabularInline in admin.py
can you please help me with the below query in django TabularInline: In models.py, I have model A and B class A (models.Model): Name = models.CharField(max_length=100) Location = models.CharField(max_length=100) def__(str)__(self) : return "%s" %(self.Name) class B(models.Model): Name = models.ForeignKey(A, on_delete=models.cascade) Added_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Added_by") Added_date = models.DateTimeField(default=datatime.now) Modified_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Modified_by") Modified_date = models.DateTimeField(editable=False,blank=True) In admin.py , class B_admin(admin.TabularInline): model = B extra = 0 readonly_fields=["Added_by","Added_date","Modified_by","Modified_date"] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) def save_model(self, request,obj form, change): if getattr(obj, '', None) is None: obj.Added_by = request.user obj.Modified_by = request.user obj.Added_date = datetime.now() obj.Modified_date = datetime.now() else: obj.Modified_by = request.user obj.Modified_date = datetime.now() obj.save() class A_admin (admin.ModelAdmin): Inline = [B_admin] list_display = ['Name','location'] list_filter = ['Name','location'] search_fields = ['Name','location'] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) Here , the admin page A is working fine with Model B as TabularInline. Also, the readonly_fields looks good inside TabularInline. Now the problem is when the admin page gets saved , the readonly_fields(Added_by,Modified_by,Modified_date) are showing blank and are not getting autopopulated . Added_date is working correctly since i have mentioned default=datetime.now while declaring inside model B. Other 3 fields are not getting autopopulated. Kindly assist me in this . Thanks in … -
How can i add an item to a user in django (rest framework)
I have a Teammodel and a Usermodel. Every User can belong to one or more Teams. The creation of a user with a Team is working fine. But i want to add a existing user to a existing Team. I tried several options but for every option i get an error. The Models: class Teams(models.Model): name = models.CharField(max_length=20) file = models.FileField(upload_to='team_icons', null='True', blank='True') members = models.ManyToManyField(User, related_name='member') def __str__(self): return self.name **The Serializers:** class UserSerializer(serializers.ModelSerializer): member = serializers.PrimaryKeyRelatedField(many=True, queryset=Teams.objects.all()) class Meta: model = User fields =['id', 'username', 'owner', 'password', 'todos','member', 'email', 'first_name', 'last_name',] The View class AddUserToTeam(generics.RetrieveUpdateDestroyAPIView): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer permission_classes = [permissions.AllowAny] So i want: user.member.add(x), x is the team where user had to be added to -
How to display data dynamically with ant design tables
first please my javascript skill level is not good, but here... I have a table i got from ant.design, im trying to build a frontend with react, so I want to display some data on the table from my database but im finding it had because of the want ant design table is set up. This is the code class OrderSummary extends React.Component { render() { const columns = [ { title: 'Number', dataIndex: 'number', key: 'number', render: text => <a>{text}</a>, }, { title: 'Event Name', dataIndex: 'name', key: 'name', }, { title: 'Event Price', dataIndex: 'price', key: 'price', }, { title: 'Quantity', dataIndex: 'quantity', key: 'quantity', }, { title: 'Total', dataIndex: 'total', key: 'total', }, ]; const datasource = {data.order_items.map((orderItem, i) => { return ( [ { key: {orderItem.id}, number: {orderItem.item.title} -{" "}, name: 32, price: 'NGN' {orderItem.item.price} , quantity: {orderItem.quantity}, total: {data.total}, }, // { // key: 1, // name: 'John Brown', // age: 32, // address: 'New York No. 1 Lake Park', // tags: ['nice', 'developer'], // }, ]; return ( <Layout> <div> <PageHeader className="site-page-header" onBack={() => null} title="Order Summary" /> <Table columns={columns} dataSource={datasource} /> </div> </Layout> ) } }; export default OrderSummary; Note where i commented … -
I have a problem when testing my api on localhost everything went okay however when deployed to dev server and need to test it I get KeyError 'Date'
class Prayers(APIView): parser_classes = (JSONParser,) permission_classes = (rest_permissions.AllowAny,) def get(self, request): """ API for the visitorstrong text to get all prayers paginated """ data = helpers.dict_filter(request.query_params.dict(), 'date','nbdays') if "nbdays" in data : days=timedelta(days=int(data['nbdays'])) if "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) date=date+days else: today=datetime.now() date=today+days elif "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) days=timedelta(days=30) date=date+days else: today=datetime.now() days=timedelta(days=30) date=today+days serializer = PrayerSerializer( models.Prayer.objects.get(pk=date) ) response = { "prayer times": serializer.data, } return Response(response, status=status.HTTP_200_OK) 'API to get prayers time through filtering' -
How to avoid repetition in Django model fields?
I have models that share many common fields. For example: class Customer(models.Model): name = models.CharField() email = models.CharField() address = models.CharField() phone = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() wallet = models.FloatField() class Seller(models.Model): # same fields from Customer class, except the field wallet To avoid repeating these fields, I have tried to create classes with these common fields and link using OneToOneField: class ContactInformation(models.Model): phone = models.CharField() email = models.CharField() class AddressInformation(models.Model): address = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() class Customer(models.Model): wallet = models.FloatField() contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) class Seller(models.Model): contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) But now it gets very messy if I try to create a ModelForm based on the Customer, as there is only the wallet field in it. To display my other OneToOneFields I have to create multiple forms: a form for the contact information and another for address information, as ModelForms don't simply display these OneToOneFields as a single form. The views get bloated, as I have to validate 3 forms in total and have to manually create the object instances. Am I missing something here? Should I use inheritance instead? Should I … -
Get and assign elements in variables from a Nested List in Python
i'm working with a nested list in python like this list[[a,b,c,d,e],[a,b,c,d,e]] every element is composed ever of 5 parts, the content of the list can change in amounts of elements it can be from 1 to 10 elements max. Here came the difficult for me, cause I need to assign any part of every element into one individual variable, and when the element end, move to the next element,but before move send variables to one function that insert data in the oracle database. It is a part of a function in python django web app. The idea is to separate the data received in form a list after that send it to a stored procedure. This is part of the code. enter code here acomp = '' acomp = request.POST.getlist("acomp") split_strings = [] #Here divide the list in 5 parameters that are the rows of the table in #oracle n = 5 for index in range(0, len(acomp), n): #Creamos una lista anidada para dividir los datos de los acompañantes por cada uno split_strings.append(acomp[index : index + n]) #ow I can seperate the data assign every element into a variable and send it to the function that will insert it in … -
how to show images from serializers list in django using jquery ajax
I want to show image from serializers list view using jquery . I wanted to show all the tweets using ajax but i have no idea how to show image using jquery ajax models.py class Tweet(models.Model): content = models.CharField(max_length=140) author = models.ForeignKey(User,on_delete=models.CASCADE) Image = models.FileField(upload_to="images/",blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) serializers.py class TweetModelSerializers(serializers.ModelSerializer): author = UserDisplaySerializer() class Meta: model = Tweet fields = ['content','author','Image'] views.py class TweetListAPIView(generics.ListAPIView): serializer_class = TweetModelSerializers def get_queryset(self,*args,**kwargs): qs = Tweet.objects.all().order_by("-timestamp") print(self.request.GET) query = self.request.GET.get("q", None) if query is not None: qs = qs.filter( Q(content__icontains=query) | Q(user__username__icontains=query) ) return qs jquery $.ajax({ url:"/api/tweet", method:"GET", success: function(data){ //console.log(data) $.each(data,function(key,value){ //console.log(key) console.log(value.Image) var tweetContent = value.content; var tweetUser = value.author; var tweetImage = value.Image; $("#tweet-container").append( "<div class=\"media\"><div class=\"media-body\">" + tweetContent + "<br/> via " + tweetUser.username + " | " + "<a href='#'>View</a>"+"<br>" + tweetImage + "</div></div><hr/>" ) }) }, error:function(data){ console.log("error") } }) this method doesnot show the image. It only show the name of the images like http://127.0.0.1:8000/img/images/FB_IMG_1538467390993.jpg . How can i show the images in jquery ? -
Django actual value in choice field form
I have models like this: class Projects(models.Model): project = models.CharField(max_length=150, blank=True, null=True) def __str__(self): return self.project class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) project = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username I also made a form in which I want to change current Project assigned Profile: class ProjectForm(ModelForm): class Meta: model = Profile fields = [ 'project' ] My view looks like this: def change_project(request, user): user = User.objects.filter(username=user)[:1].get() profile = Profile.objects.get(user=user) form = ProjectForm(request.POST, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() context = {'form': form} return render(request, 'datafiller/change_project.html', context) I can change the project using this form, but every time I want to do it again the form looks like this How can I show in the form the current project instead of "------"? -
How to create a custom templatetag in my django project
I have been trying create a custom templatetag in my project , but it does not work This is my structured project : I created a folder in my index directory called templatetags > __init__.py , extras.py , inside extras file this: from django import template register = template.Library() def cut(value): return value.replace("no", 'yes') Template : {% load poll_extras %} but I got this -
CSS inheritance in Django templates
I want to split my CSS to multiple files to match with each template and app. But the following problem keeps me baffled. In the base.css of my base.html template, I have an element class button declared as following: .button { ... } So, all buttons should follow this css. In an app called table, in a template table_view.html that extends base.html {% extends "base.html" %} {% load static %} {% block content %} <link href="{% static 'css/table.css' %}" rel="stylesheet" /> ... <button class="btn-avail table">Table</button> ... {% endblock %} I have a different format for class btn-avail in table.css. But I could not get it to load and override the base format. If I change the class name to button (of base.css), then it reflects the base format. Or if I place btn-avail in the base.css, then its format is correctly reflected. In my settings.py, here is my static directory: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') What am I doing wrong? Thanks. -
Hi All! I'm getting a "Bad Request (404)" error after deploying a Django app to Heroku
This is my first question on Stackoverflow so please bare with me. I've been trying to deploy a Django app to Heroku using AWS S3 as the place for my media storage. I've gone through what's neccesseryto get everything up and running (see settings.py code below) but can't figure out why I keep hitting the "Bad Request (404)" error page. Here's part of my heroku logs --tail traceback. I originally thought the issue was with Gunicorn but all seems to be fine there. If you need to see the rest please let me know as SO wont allow me to post the full traceback. 2020-10-30T18:20:28.057488+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=8daaabd0-3f8d-4f87-847e-25291d4372fc fwd="176.26.119.21" dyno=web.1 connect=1ms service=193ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.058801+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET / HTTP/1.1" 400 143 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:28.352784+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=fryed-project.herokuapp.com request_id=bc9d6397-6f63-4be7-a19f-826165de2cf6 fwd="176.26.119.21" dyno=web.1 connect=0ms service=127ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.353864+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET /favicon.ico HTTP/1.1" 400 143 "https://fryed-project.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:42.832461+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=34319de1-399e-4c72-91b4-c9c3a173c0f7 fwd="176.26.119.21" dyno=web.1 connect=0ms service=18ms status=400 bytes=476 protocol=https 2020-10-30T18:20:42.833907+00:00 app[web.1]: 10.12.135.75 - … -
Populate another input field based on another field using ajax, Django
I am trying to populate one input field based on another field. I am using raw SQL query instead of ORM. My views : def myview(request): form=searchform(request.POST) conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") rows=[] if request.method=='POST': empno = form['empno'].value() try: cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() finally: conn.close() for row in rows: employee_name=row['EMP_NAME'] context={ "rows":rows, "form":form, "employee_name":employee_name, } return render(request,"test.html", context) @csrf_exempt def ajaxviews(request): empno = request.POST.get("empno") conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() print(rows) context={ "rows":rows, } return HttpResponse(context) Urls: urlpatterns = [ path('admin/', admin.site.urls), path('test/',views.myview,name="test"), path('test_ajax/',views.ajaxviews,name="test_ajax"), ] forms: class searchform(forms.Form): empno=forms.CharField(label="empno", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) empname=forms.CharField(label="empname", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST"> {% csrf_token %} <p><label for="id_empno">empno:</label> <input type="text" name="empno" class="form-control" maxlength="50" required="" id="id_empno"></p> <input type="Submit" name="submit" value="Submit"> </form> <p><label … -
Django 3: How to pass 'rows' into the html template?
I'm building a Crud table template as the user has many many tables to update and I'm having trouble passing on the records to the template. Here is my view: def crud_table(request): user = request.user org = Organization.objects.filter(user=user) active_project = Project.objects.filter(organization=org[0], is_active=True)[0] assets = Asset.objects.filter(project=active_project) context_lbls = {'name': 'Name', 'asset_id': 'Asset ID', 'det_curve': "Deterioration Curve", 'class': 'Class', 'surface_type': 'Surface Type', 'Age': 'Age', 'AADT': 'AADT', 'AADTT': 'AADT', 'route': 'Bus Route', 'truck_route': 'Truck Route', 'Length': 'Asset Length', 'HCI': 'HCI' } context_data = {'name': Asset.objects.filter(project=active_project), 'asset_id': assets.asset_id, 'det_curve': assets.det_curve.name, 'class': assets.func_class.name, 'surface_type': assets.surface_type.name, 'Age': assets.age, 'AADT': assets.aadt, 'AADTT': assets.aadtt, 'route': assets.is_bus_route, 'truck_route': assets.is_truck_route, 'Length': assets.length, 'HCI': assets.hci } context = {'labels': context_lbls, 'records': context_data} And here is my template: <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> {% for l in labels %} <th>{{l}}</th> {% endfor %} </tr> </thead> <tbody> <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> {{ records }} {% for r in records %} <td>{{r}}</td> {% endfor %} </tr> </tbody> My context_data is obviously incorrect, I'm just not sure how to pass the information to the template. I'm doing all of this to avoid having to create multiple HTML files and … -
Django: Sum of annotated field
I have the following two models: class ProductionSet(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) line = models.ForeignKey(Line, on_delete=models.CASCADE) class ProductionSetEntry(models.Model): productionset = models.ForeignKey( ProductionSet, on_delete=models.CASCADE, related_name="set" ) audited_at = models.DateTimeField( verbose_name=_("Audited at"), null=True, blank=True ) What I want to achieve is a result set grouped for each line with two counts: an entries total count and a count for fully audited sets. Sample result: <QuerySet [{'line': 1, 'sum_fully_audited': 0, 'total': 43}, {'line': 2, 'sum_fully_audited': 0, 'total': 51}, {'line': 3, 'sum_fully_audited': 2, 'total': 4}]> I'm able to add the fully_audited to each row before grouping by: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ) Following query: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), sum_fully_audited=Sum("fully_audited"), ).order_by( "line" ) raises django.core.exceptions.FieldError: Cannot compute Sum('fully_audited'): 'fully_audited' is an aggregate while ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), ).order_by( "line" ) results in <QuerySet [{'line': 1, 'fully_audited': 0, 'total': 43}, {'line': 3, 'fully_audi... which looks good so far but obviously has no sum_fully_audited yet. -
How to integrate Opencv in Django rest frame
I have a simple opencv file that converts frames to video. I fetch video from Django db and convert to frame. Now my question is how can I save the converted frames in the directory where my video is.? I get this error when I try to use the uoload_to function as a save path in the video_to_frame function cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) TypeError: expected str, bytes or os.PathLike object, not function Upload directory def upload_to(instance, filename): base, extension = os.path.splitext(filename.lower()) return f"SmatCrow/{instance.id}/{filename}" Model.py from .utils import video_to_frame class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): super(MyVideo, self).save(*args, **kwargs) tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) Opencv def video_to_frame(video): today = date.today() d = today.strftime("%b-%d-%Y") cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() -
Ignoring a Django signal with a test mock
I have a function setup to hook the pre_delete on a model and I want to ignore this during testing using unittest.mock.patch, but this only works when I use the signal name from Django or if I disconnect it by dispatch_uid. The prototype looks like: @receiver(pre_delete, sender=MyModel, dispatch_uid="pre_delete_my_model") def pre_delete_my_model(sender, instance, *args, **kwargs): ... in my tests this works: @patch("django.db.models.signals.pre_delete") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... but I'd like something that's a bit more explicit, eg. @patch("my_app.signals.pre_delete_my_model") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... this doesn't work though, I assume because that's not the signal that's being raised, it's just set up to receive it. I have found a way that works using pre_delete.disconnect(...), but I'm an annoying person that doesn't like the way that looks with those calls spread around my tests. Is there a way to do this so that it can use something specific to the model or the handler in the decorator? -
Displaying tabular data using columnar with python
I have the structure as follows. I show it as a table with the columnar library. It works just fine. But because the incoming json data is "dict", it does not show it as a single line. How can I show the above json data in single print (table) print screen? from time import sleep from django.views.decorators.http import require_POST import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import django_filters.rest_framework import requests from columnar import columnar from tabulate import tabulate @require_POST @csrf_exempt def webhook(request): while True: get_active_position() return HttpResponse(request, content_type='application/json') def get_active_position(): print("get_active position") data = "{'symbol': 'BCHUSDT', 'positionAmt': '0.001', 'entryPrice': '266.85000', 'markPrice': '259.99000000', 'unRealizedProfit': '-0.00686000', 'liquidationPrice': '0', 'leverage': '20', 'maxNotionalValue': '250000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} {'symbol': 'ETHUSDT', 'positionAmt': '0.001', 'entryPrice': '385.88000', 'markPrice': '381.85854735', 'unRealizedProfit': '-0.00402145', 'liquidationPrice': '0', 'leverage': '10', 'maxNotionalValue': '2000000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} " for sym in data: if sym['positionAmt'][:1] == "-" and sym['positionAmt'] <= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) # Long position elif sym['positionAmt'] >= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) return … -
ImportError: attempted relative import with no known parent package while running code
Code: from django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import BookForm from .models import Book from django.db import models On running code i am getting this error **Output: ** Traceback (most recent call last): File "/media/programmer/New Volume/Projects/TradeCred/backend.py", line 6, in <module> from .forms import BookForm ImportError: attempted relative import with no known parent package -
How to make no-reply@company.com in Django
i have a problem, when i sent email, my host user email is the sender, i want no-reply@company.com is the sender if customer see the email, #views.py email_body = 'Hallo '+user.username + 'Silahkan login akun anda, dan print surat yang anda ajukan' email_subject = 'Pengajuan Surat Diterima' email = EmailMessage( email_subject, email_body, 'Kecamatan Bintan Utara <noreply@kantorkecamatanbintanutara.com>', [user.profile.email], ) email.send(fail_silently=False) context = { 'form3':form3, 'form4':form4, 'code':code } #setting.py EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = 'akuntest1291@gmail.com' EMAIL_HOST_PASSWORD = 'krnhbjfcczgrfutp' EMAIL_USE_TLS = True EMAIL_PORT = 587 -
Newer Django requires applying migration, what are the changes in database
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project seems to be running OK, but with message saying: ... Performing system checks... System check identified no issues (0 silenced). You have 5 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, sites. Run 'python manage.py migrate' to apply them. ... Following the message, I applied the migrations by command python manage.py migrate, and the message disappeared when starting again. The legacy project is already running on an existing database for production, so I'm wondering: What changes did the migrate make into database? Is there some way to compare (MySQL) database before and after applying the migration? I'm new to Python upgrade, so is there any important things to check for this type of migrate upon existing database? Any thoughts will be highly appreciated. More details, if interesting to you: Screenshot of applying migration: " (venv) [appuser@testserver PROJECT]$ python manage.py migrate /data/EBC-dev/venv/lib/python2.7/site-packages/arrow/arrow.py:28: DeprecationWarning: Arrow will drop support for Python 2.7 and 3.5 in the upcoming v1.0.0 release. Please upgrade to Python 3.6+ … -
Django - Adding text from dictionary in a static tag
In Django, I have this line in my HTML file which adds an image using the static tag. However, it seems like {{ dictionary.key }} is not working in this case. <img src="{% static 'Image/Portfolio/{{article.slug_title}}/{{article.imageFile}}.jpg' %}"> Is there any method to solve this problem or it is possible to like with the absolute route? Thank you. -
Problemas para usar el FilteredSelectMultiple de Django
soy algo nuevo con django, y tengo el problema de que cuando utilizo FilteredSelectMultiple de django en mis propias vistas, no se muestra como cuando se asignan permiso en el admin de django, sino mas bien esto:enter image description here En mi Forms.py tengo esto: class GroupForm(forms.ModelForm): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) class Meta: model = Group fields = '__all__' En mi Views.py: class GrupoRegistrar (LoginYSuperStaffMixin, ValidarPermisosMixin, CreateView): model = Group form_class = GroupForm template_name = "Grupos/registrar_grupos.html" permission_required = ('', ) def post(self, request, *args, **kwargs): if request.is_ajax(): form = self.form_class(data= request.POST, files= request.FILES) if form.is_valid(): form.save() mensaje = f'{self.model.__name__} registrado correctamente' error = 'No existen errores' response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 201 return response else: mensaje = f'{self.model.__name__} no se ha podido registrar!' error = form.errors response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 400 return response return redirect ('empleado:grupos_inicio') en mi html: <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title">Registro de Grupos de permisos</h2> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {{ form.media }} <form id="form_creacion" action="{% url 'empleado:grupo_registro' %}" method="POST"> {% csrf_token %} <div class="modal-body"> <div id="errores"> </div> {{form}} … -
Accessing a public text file by passing a key in Django
I am looking to host a text file that will be publicly accessible on a Django application: http://www.example.com/textfile However, when someone is accessing this text file, they need to to pass an access key, e.g http://www.example.com/textfile?accesskey=123456 The access key is only known to members who are allowed access to this file. The reason for doing it this way is that I have a 3rd party legacy device that can only read text files, and I need to protect the file somehow. Is it possible to run this in Django urls.py? Any help is really appreciated. -
API Django Rest Framework on Cloud Run shutting down
I have implemented an API DRF on Cloud Run. The Dockerfile is the following: # Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.7-slim # Allow statements and log messages to immediately appear in the Cloud Run logs ENV PYTHONUNBUFFERED True # Prevents Python from writing pyc files to disc (equivalent to python -B option) ENV PYTHONDONTWRITEBYTECODE True ARG REQFILE=base.txt ENV REQFILE ${REQFILE} # install dependencies RUN pip install --upgrade pip # Copy application dependency manifests to the container image. # Copying this separately prevents re-running pip install on every code change. COPY requirements/*.txt ./ # Install production dependencies. RUN pip install -r ./${REQFILE} # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app It is the same as described in the documentation : https://codelabs.developers.google.com/codelabs/cloud-run-django#6 But since a few days, without any significative change on my code, I have …