Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
verbose_name_plural not working as in django admin
I am trying to change display for Model name in my django admin using verbose_name_plural in class Meta. here is my code : class Country(models.Model): country_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.country_name class Meta: verbose_name = "Country" verbose_name_plural = "Countries" But it is not working, the display name is not changed in django admin list. django-admin list models I also tried to : place the "Meta" class in admin.py -> not working already makemigrations & migrate -> still same result stop and start server Thank you for any comment/advice. -
how i solve Class 'Like' has no 'objects' memberpylint(no-member)
**In My models classes occure error Class '' has no 'objects' memberpylint(no-member) in al; models classes so how i solve this error can you tell me below example like class in cls is occured above error ............................................................................................................................................................................. ** models.py class Like(models.Model): user = models.ManyToManyField(User,related_name="linkingUser") post = models.OneToOneField(Post,on_delete=models.CASCADE) @classmethod def like(cls,post,liking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.add(liking_user) @classmethod def dislike(cls,post,disliking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.remove(disliking_user) -
Get value from dropdown and use it for post method within view
Hi there another Django newbie here, So, I'm trying to make a simple Quote web application. So, I have 2 models: 1 for an Author and another 1 for Quotes. So there is a many to one relationship: Author model: ```class AuthorInfo(models.Model): author_firstName = models.CharField(max_length=100) author_lastName = models.CharField(max_length=100) def __str__(self): return self.author_firstName``` Quote model: ```class Quote(models.Model): author = models.ForeignKey(AuthorInfo, on_delete=models.CASCADE) quote_text = models.CharField(max_length=255) def __str__(self): return self.author.author_firstName``` What I'm trying to do right now is, I have a form and inside that form, I have a dropdown that is filled up with the author's first names. Form inside Home.html: ```<form method="POST" action="/addQuote/"> {% csrf_token %} <div class="container mt-3 d-flex justify-content-center"> <div class="card w-100"> <div class="card-header navbar-dark bg-primary"> <h1 style="color: white;">Add quote</h1> </div> <div class="card-body"> Quote text <div class="input-group input-group-sm mb-1"> <div class="input-group-prepend"> <span class="input-group-text bg-primary" style="color: white;" id="inputGroup-sizing-sm" >Enter Quote</span > </div> <input name="quote_text" type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" /> </div> <br /> <div class="mb-3"> <div class=""> Select author <select name="dropdown_author"> {% for author in authors %} <option value="{{author.author_firstName}}" >{{author.author_firstName}}</option > {% endfor %} </select> </div> </div> <button type="submit" class="btn btn-primary align-items-center d-flex justify-content-center" > Submit quote </button> </div> </div> </div> </form>``` I want to make it possible for … -
Storing multiple images per each entity object in Django with SQLite
I am currently building myself a website that I could store info of recently release hardware parts (e.g. Motherboard, CPU, etc.) I am super newb on Web Development and here is my code snippet of current database model. class Manufacturer(models.Model): name = models.CharField(max_length=264, unique=True) class Hardware(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) name = models.CharField(max_length=264, unique=True) price = models.DecimalField(max_digits=6, decimal_places=2) release_date = models.DateField(default=datetime.date.today) image = models.ImageField(null=True, blank=True) class Meta: abstract = True So, this way I could have stored zero or one image per each entity, but ain't sure how I could make it to store 0 to more images per each. It seems like PostgreSQL does support an ArrayField, but since I am using SQLite, I can't really think of the best way to achieve this. -
I am trying to make a JS function inside of a button within a Django app that deletes a related database (SQLite3) entry
I have a Django localhost webserver that I've been experimenting with, and I'm doing the infamous "todo app" as my intro to a few topics. Conceptually, the user puts their "todo item" into a text input field (which is a Django form that's inside of the django html template). This action takes the text and puts it in a SQLite3 database and at the same time, the action creates a div container that has a paragraph tag and a button inside of that div. The P tag gets filled with the contents of the text given in the input. The button is meant to do two things; firstly, it deletes the parent div, which removes that button and the todo item. So, it's like a "this item is done" button, which deletes that item. That is working properly. The SECOND function of the button, though, has got me stumped. The idea is to delete that item from the database as well, as that's where I store and retrieve the todo items from when the page is generated. I have attempted to do this by passing the {item} variable (which is a Django Template Language variable made inside of the Django … -
Gcloud deleted instance without removing ssl-certificates now my PSQL port 5432 is locked
I was trying to post a site on gcloud, we set everything up on Django SSL and all but, the File was over 10000 so it did not work. I wanted to migrate to AWS and use elastic beanstalk the issue is. I'm locked out of PSQL/port can not even run my site on local port 5432. psql: error: could not connect to server: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0074D/100) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? {gcloud compute ssl-certificates delete} `ERROR: (gcloud.compute.ssl-certificates.delete) Could not fetch resource: - The resource 'projects/firstsitempc/global/sslCertificates/firstsitempc' was not found ` -
Is there a simple way to provide code coverage for django/django rest framework views?
When rendering DRF views using coverage on a Django system, I'm not seeing hits on the internals of my functions. I am seeing hits on the definition of my class/function as those are imported into the tests (which is expected). Is there a general strategy to use in order to achieve coverage reports for Django or DRF views? So far I've been struggling to find any answers here. The code I"m using is similar to the example I'm providing below # API File referenced as afile below. from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.response import Response class MyView(APIView): def post(self, request: Request) -> Response: return Response(resp, status=200) # Test file referenced below. from afile import MyView from django.test import TestCase from rest_framework.test import APIRequestFactory class TestView(TestCase): def test_thing(self): factory = APIRequestFactory() request = factory.post("/fakeurl", {}) response = MyView.as_view()(request) self.assertEqual(response, 200) I understand that most black box testing strategies shouldn't render code coverage. But, since I am calling a Django view via the functionas_view() I am curious as to whether I should expect hits on my code. -
turn each django table row into link
I have a django table2 table and I need to make each row of one column to be a link toward others urls. Django tables 2: Hyperlinking items in a column is the closest thing that I found but it does not work for me. my table looks like this: Class revenue nb_items classAA 10 3 classA 8 4 classB 6 7 classC 4 11 classD 2 17 but I cannot find a way to make the classes a clickable link to a corresponding page that I have. From what I found online, I have tried something like this: class ClassificationTable(tables.Table): Class = tables.LinkColumn('classAA1page.html', args=[class_aa1('pk')]) but this solution does not work because it only let me code one link and not one for EACH row of the table. I am hoping that someone could provide me with some guidance on the matter. Thank you! -
enabling a django download button for pdf download
I am trying to set up a django button so I can download a file. I tried following along a tutorial but I think i'm missing something. The urls.py code below is the urls.py file that i generated in the app section of my project. I am not sure if that is the correct one to be using. The code below is not working, local host doesn't load the page. however when i comment out url('download_my_pdf', download_pdf), in my urls.py the site loads as we dont have that link back to the code in the views. INDEX.HTML: <input type="button" value="Download" onclick="window.open('download_my_pdf')"> VIEWS.PY: from django.shortcuts import render from django.http import HttpResponse from wsgiref.util import FileWrapper def index(request): return render(request, "index.html", {}) def home(request): return render(request, "home.html", {}) def download_pdf(request): filename = 'faults.pdf' content = FileWrapper(filename) response = HttpResponse(content, content_type='application/pdf') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename=%s' % 'faults.pdf' return response URLS.PY from django.urls import url from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('home', views.home, name="home"), url('download_my_pdf', download_pdf), ] -
how do i add number and string to my django
hey someone should kindly help me out with my code,how can i add number and text randomly to my model.py ,actually i have website with a user profile which when the user subscribe it will generate a random text and number to the user profile that will serve the user like an id till the subscription is over,here is my code models.py def plan_id(): plan_id=[] for i in range(5): alpha=random.choice(string.ascii_letters) num=random.choice(string.digits) plan_id.append(alpha) plan_id.append(num) y = "".join(str(x)for x in plan_id) return str(random.choice(string.y)) class Patient(models.Model): STATE_CHOICES=( (True, u'Yes'), (False, u'No'), ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=True, choices=STATE_CHOICES) plan_id = models.CharField(max_length=10, null=False, default=plan_id) views.py @login_required def patient(request): context = { 'patient': Patient.objects.all() } return render(request, 'pages/patient.html', context) -
Adding img tags into a Django template using Javascript
Hi so I am trying to make a website in django. For one page on the website I want to have a catalog so I need to load in a big table using javascript. The console.log is the correct img tag syntax but no images load. This is my javascript code : catolog.js function makeList() { listData = Array.from(Array(43).keys()); // Add it to the page content1 = document.querySelectorAll(".tg-0lax"); var count = 0; var td; for (td of content1){ console.log(td); text = 'images'+ '/'+ 'image_' + count + '.jpg'; console.log(text); img = " src= \"{ % static '" + text + "' % }\""; str = '<img ' + img + '>'; console.log(str); td.innerHTML = str; count = count + 1; } } makeList(); This is my html file {% extends "storeApp/base.html" %} {% block content %} {%load static%} <style> article{ text-align: center; } </style> <div class="content1" id="data-point-1"> <style type="text/css"> .tg {border-collapse:collapse;border-spacing:0;} .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; overflow:hidden;padding:10px 5px;word-break:normal;} .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;} .tg .tg-0lax{text-align:left;vertical-align:top} </style> <table class="tg" onload="makeList()"> <thead> <tr> <th class="tg-0lax"></th> <th class="tg-0lax"></th> <th class="tg-0lax"></th> </tr> </thead> <tbody> <tr> . . . </tr> </tbody> </table> <script src={% static 'js/catolog.js'%}> </script> </div> {% endblock %} -
TypeError: expected string or bytes-like object with django Q query
I'm trying to filter Event objects to only show events where the event.day is greater than or equal to today. However, I get the following error when I run it: TypeError: expected string or bytes-like object views.py today = datetime.now().day availability = Event.objects.filter(Q(day__gte=today)).order_by('-day') the day field in the Event model is a DateField. Any help would be greatly appreciated. Thanks! -
Django + PostgreSQL backup and restore on an EC2 instance
I have a simple monolithic architecture: A Django project hosted on an EC2 instance, talks to a PostgreSQL DB running on the same instance. I chose this architecture considering the traffic and cost. So, don't bash me on this one. :) For disaster recovery, I regularly dump my DB (a full dump pg_dump -U postgres fishercoder_db > fishercoder_dump.sql). At restoring, I cannot get Django and the restoring DB to talk nicely with each other: If I launch Django and run ./manage.py migrate first, and then restore the DB from the dump, it fails because Django has already created a bunch of internal tables after running ./manage.py migrate which have exactly the same name of in my dump; If I restore the DB from the dump first, then my Django app cannot stand up because of insufficientprivilege to run ./manage.py migrate, details asked here. My question is: Is my DR strategy reasonable? Any other more optimal ways? How can I get this approach to work: restore my site on a new EC2 instance with DB restored from a .sql dump. -
Displaying PPT in HTML web page
Currently creating an website using Python django framework using HTML and one of the features is file upload & view. It works fine with PDF documents, but when I try to view uploaded PPT documents, it always goes to download in chrome browser Few things I tried and didn't prefer are, 1) Using Embed PPT from Onedrive which supports already available documents. 2) Changing the PPT file into some other document format like PDF and viewing it directly from browser Please let me know how to view/display PPT file in HTML webpage without going through above complications. -
Django model history with foreign keys history tracking using django-simple-history
I have three models with historical records: class WifiUser(models.Model): .... wifiDevice = models.OneToOneField(WifiDevice, on_delete=models.CASCADE, default=None) wifiSim = models.OneToOneField(WifiSim, on_delete=models.CASCADE, default=None) history = HistoricalRecords() class WifiDevice(models.Model): .... history = HistoricalRecords() class WifiSim(models.Model): .... history = HistoricalRecords() I want to keep track of history with corresponding foreign key history records. But when accessing the history of Wifiuser I get the latest values of WifiDevice and WifiSim. I want the historical record of WifiDevice and WifiSim to point to that record of their one. Whats the best method to follow for this ? -
Sort db alphabetically with header in django
Writing website on django: i've got 1500 rows in DB Need to give those rows to frontend like: A Alice Andrew Ann B Bill Boris Brendan ... now in my views.py the for cycle goes around names and if the first letter of name is in the alphabet, that letter is added to my new alphabet: for name in names: if name[0] in alphabet: my_alphabet.append(name[0]) my_alphabet = sorted(list(set(my_alphabet))) Then I transfer my new alphabet and names to the html template: {% for letter in my_alphabet %} <span>{{ letter }}</span> {% for name in names %} {% if name.0 == letter %} <span>{{ name }}</span> {% endif %} {% endfor %} {% endfor %} That pages loads up to 10 seconds Maybe anyone's got a faster variant? Thanks for helping noob, sorry for wasting time! -
Django: Referencing inherited attributes from mixin
I have a long list of tuples used as model choices. They are currently class attributes in a model definition. I would like to move them into a mixin without affecting existing references across a legacy codebase. Here is what currently exists: class MyModel(models.Model): COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) status = models.IntegerField(choices=STATUSES) Here is what I would like to do: class StatusMixin: COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) class MyModel(StatusMixin, models.Model): status = models.IntegerField(choices=STATUSES) I'm trying to reference them: As part of the model inheriting them: my_model_instance = MyModel.objects.get(id=1) if my_model_instance.status == MyModel.FIRE: return As part of a model NOT inheriting them, but referencing the model that does: class OtherModel(models.Model): my_model_status = models.IntegerField(choices=MyModel.STATUSES) I am unable to satisfy both conditions. I'm sure there is a better way -- perhaps not a mixin? -
Implement python-social-auth with Django and Steam backend
not sure how to start this thread but i implemented the Python-Social-Auth to work with Github, i followed this tutorial and i got it working: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html So i decided ok why we don't make it with Steam and i found this: Proper way to implement python-social-auth with Django and Steam backend Bad news about it is that, i make everything i guess not sure if i have to do anything else, when i click login into Steam and i go to the https://steamcommunity.com/openid/login but when i get back to the website i get this at console: [19/Jun/2020 17:25:10] "GET /oauth/login/steam/ HTTP/1.1" 200 1230 [19/Jun/2020 17:25:52] "GET /oauth/complete/steam/?janrain_nonce=2020-06-19T21%3A25%3A10ZdgR4aL&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.return_to=http%3A%2F%2F127.0.0.1%3A8000%2Foauth%2Fcomplete%2Fsteam%2F%3Fjanrain_nonce%3D2020-06-19T21%253A25%253A10ZdgR4aL&openid.response_nonce=2020-06-19T21%3A25%3A50ZQ9%2F%2BHcdLB5lfPjbsYvmGpLCgSe0%3D&openid.assoc_handle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=SLkLPpwAJyW8q9Ftp9bKlp8m%2Bys%3D HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET / HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET /login/?next=/ HTTP/1.1" 200 193 And never login, i go back and still says Login with steam or Github so i decided to check the database and i found that the entries are even added to it... Database Picture Any place where i can find help about this? Or anything that i might be missing? Thanks in advance! =) -
Django ListView filter objects
I have a simple structure Shop_list --> Product_list --> Product_detail I want to filter Product class object by slug field, but I see zero products. I think that the problem in get_queryset() views.py class HomePageView(ListView): model = Shop template_name = 'blog/shop_list.html' page_kwarg = 'shop' context_object_name = 'shops' class ProductListView(ListView): model = Product template_name = 'blog/product_list.html' page_kwarg = 'product' context_object_name = 'products' def get_queryset(self): pattern = str(self.request) pattern = pattern[1:] slug = self.model.shop return Product.objects.filter(shop__slug=pattern) def produt_detail(request, **kwargs): print(request) product = get_object_or_404(Product, pk=kwargs["pk"]) return render(request, 'blog/product_detail.html', {'product': product}) models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) slug = models.SlugField(null=False, default="Shop") def get_absolute_url(self): return reverse('product_list', kwargs={'slug': self.slug}) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="shop") title = models.CharField(max_length=200) price = models.CharField(max_length=200) period_start = models.DateTimeField(blank=True, null=True) period_end = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse('product_detail', kwargs={'slug': self.shop.slug, 'pk': self.pk}) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='shop_list'), path('<slug:slug>', ProductListView.as_view(), name='product_list'), path('<slug:slug>/<int:pk>/', views.produt_detail, name='product_detail'), ] product_list.html {% for product in products %} <a href="{% url 'product_detail' product.shop.slug product.shop.pk %}"> ... -
filter blogs by tags in Django
I'd like to render a view in Django with objects that have certain tags. Here's my model: class Tag(models.Model): """Model representing a tag.""" name = models.CharField(max_length=200) class Post(models.Model): """Model representing a post.""" title = models.CharField(max_length=200) # ManyToManyField used because tag can contain many posts. Posts can cover many tags. tag = models.ManyToManyField(Tag, related_name='tags', blank=True, default='', help_text='Select a tag for this post') after running migrations, I see three tables generated in my DB: blog_tag, blog_post and blog_post_tag blog_post table doesn't contain a column called tag, instead, this blog_post_tag holds all the mapping. What I'd like to achieve is to find all posts that have certain tags. I tried to use post_list = Post.objects.filter(tag__in=['AWS']), but this one throws Field 'id' expected a number but got 'AWS'. Any help on working this out would be greatly appreciated! -
Django slugfield changes unicode characters when saving and causes reverse no match error
I'm trying to create Unicode slugs with Django. The problem arises when it tries to save and resolve URLs with said slugs with Unicode characters in it. When I checked, Django seems to modify the characters when SlugField is used. This is my models.py: class Post(models.Model): title = models.CharField() slug = models.SlugField(unique=True, blank=True, allow_unicode=True) And I use slugify(slug, allow_unicode=True) to auto-generate slug from title. So to test this I used தமிழ் as title. Instead of a successful redirect to the URL /cats/test-cat/posts/தமிழ்/ Django showed NoReverseMatch exception with the following message. Reverse for 'post-detail' with arguments '('test-cat', 'zw93tz-தமழ')' not found. 1 pattern(s) tried: ['cats/(?P<cat_slug>[-a-zA-Z0-9_]+)/posts/(?P<post_slug>[-a-zA-Z0-9_]+)/$'] When I check the database, the title field has the right characters தமிழ் but the slug field has the modified characters தமழ. When I looked up for solutions, I found a workaround to use <str> instead of <slug> in urls.py. Why is this happening with <slug> and how to fix this? -
Send the logged user Profile Model to a CreateView form
what I am trying to accomplish is to send the "requester" model, using the logged-in user to a form ... Mainly the problem that I have is that the views.py "class CreateOrderView(CreateView)" does not have a parameter "request" , so I cannot get the request.user, and therefore get requester_obj and automatically select this requester_obj in the form field "requester", when entering this page. models.py Order: DEFAULT_REQUESTER_ID= 1 requester = models.ForeignKey(Profile, on_delete=models.CASCADE, default=DEFAULT_REQUESTER_ID, verbose_name="usuario") forms.py: class OrderCreateForm(BaseForm, forms.ModelForm): date = forms.DateField(label="Fecha" , widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Order fields = ['requester','title' , 'date', ] views.py: @method_decorator(staff_member_required, name='dispatch') class CreateOrderView(CreateView): template_name = 'form.html' form_class = OrderCreateForm model = Order def get_success_url(self): self.new_object.refresh_from_db() return reverse('update_order', kwargs={'pk': self.new_object.id}) def form_valid(self, form): object = form.save() object.refresh_from_db() self.new_object = object return super().form_valid(form) I get the requester like this: @login_required def create(request): #return render(request, 'app_client/create.html') if request.method == 'POST': if request.POST['value'] and request.POST['products']: logged_user = request.user user_obj = get_object_or_404(User, username=logged_user) requestor_obj = get_object_or_404(Profile, user=user_obj) .... -
Why we can't host django app like laravel in apache server? [closed]
Got a question and curious if it's possible to do ... I configured apache server and it runs .py files and print html to request while visiting localhost JUSt like how .php file sendback response . we can easily copy laravel app in htdocs and it starts from index.php in laravel framework BUT things get messy with django , you have production server comes with django framework itself, and you need to connect with with some extension to apache. why we can't do the same with python django. I can write a semi framework inside htdocs with python that works like laravel and app starts from index.py etc etc ... just like laravel, Is this kind of thing related to framework itself or it is something technical and related to language itself ? -
Is this the right format of data send over ajax
This is how my data is going via ajax request. Is this is the right format? connection: 80 trans_data[0][name]: conditional_transformation trans_data[0][display_name]: Conditional Transformation trans_data[0][trans_text]: statement trans_data[0][trans_type]: condition Because my back-end system is looking for the keyword trans_data. But due to this structure the back-end is not able to process API. -
Get Serialize data of more than 1 models
i have 3 model class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50) class DeviceType(models.Model): DeviceTypeId = models.AutoField(primary_key=True, db_column='DeviceTypeId') DeviceType = models.CharField(max_length=50) class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50) CameraId = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId', related_name='cameras') DeviceTypeId = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') i want result of Device serialize JSON data , related to Device { 'DeviceId' : DeviceId , 'DeviceName' : DeviceName , 'CameraId' : CameraId, 'CameraName': CameraName , 'DeviceTypeId' :DeviceTypeId , 'DeviceType' :DeviceType } How can i do it ?