Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to test a web application after testing on local machine
I am working on a personal project using Django. I know very little about domains and hosting. I have tested it on my own machine (http://localhost:8000/), and now I am hoping to make it live in a way where I can have a few people log onto the website from their own computers and access it. Do I need to actually host a website to do this? Or is there some equivalent version of localhost for a select few machines for testing. -
Having issue with running django server. Keep getting the following error: AttributeError: module 'django.utils.termcolors' has no attribute 'get'
I am new to Django and this is my first ever project in it. The project was running fine but I am not sure what is happening now as I keep getting the following error when trying to run the server using the command: python3 manage.py runserver Here is the full error I am getting: Traceback (most recent call last): File "/opt/anaconda3/lib/python3.7/logging/config.py", line 543, in configure formatters[name]) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 654, in configure_formatter result = self.configure_custom(config) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 473, in configure_custom result = c(**kwargs) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/log.py", line 166, in __init__ self.style = color_style() File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/color.py", line 72, in color_style return make_style(os.environ.get('DJANGO_COLORS', '')) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/color.py", line 44, in make_style format = color_settings.get(role, {}) AttributeError: module 'django.utils.termcolors' has no attribute 'get' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/i320408/Documents/Yadu/Workspace/tutorial/venv/lib/python3.7/site-packages/django/utils/log.py", line 71, in configure_logging logging.config.dictConfig(DEFAULT_LOGGING) File "/opt/anaconda3/lib/python3.7/logging/config.py", line 800, in dictConfig dictConfigClass(config).configure() File "/opt/anaconda3/lib/python3.7/logging/config.py", line 546, in configure 'formatter %r' % name) from e ValueError: Unable to configure formatter 'django.server' During handling of the above exception, another exception occurred: … -
How to integrate Node JS in Django?
I'm trying to find how to implement Node JS in Django, I have seen some posts about how powerfull can they be together Django in management and Node Js in events (like this post https://www.cuelogic.com/blog/how-to-use-both-django-nodejs-as-backend-for-your-application) but I don't know how to integrate Node JS in Django and make it work it, it said that "All you need is a way to connect the socket.io server running on Node.JS with Django app." but I have no idea how to do that, so if you guys have an idea or have had work with it before I'll appreciate if you can help to this newbie trying to be a dev. -
Django Connection timed out
I'm having a problem with Django, my program can stay idle a long time between requests to the database. Sometimes in such cases I'm receiving the following error: django.db.utils.DatabaseError: SSL SYSCALL error: Connection timed out. What can be the problem and how can I fix it? I'm using PostgreSQL with psycopg2. -
How to merge **kwargs with pipe operator?
I have a model as below: # models.py class Lorem(models.Model): # ... foo_bar = models.BooleanField() foo_baz = models.BooleanField() # ... This model has fields such as foo_bar and foo_baz. I know I will query Lorem instances where foo_bar or foo_baz is True frequently in the future. So there I go create a custom QuerySet and add it to model as_manager. # models.py class LoremQuerySet(models.QuerySet): def foo(self): return self.filter(models.Q(foo_bar=True) | models.Q(foo_baz=True)) class Lorem(models.Model): # ... foo_bar = models.BooleanField() foo_baz = models.BooleanField() # ... objects = LoremQuerySet.as_manager() Up until this point, it's fine. However, in my case, I can predict I will need other fields on my Lorem model in the future, such as foo_boo or foo_bee or whatever. And any time I add these fields, I need to manually refactor LoremQuerySet.foo() to have all the fields. # LoremQuerySet.foo() # ... return self.filter(models.Q(foo_bar=True) | models.Q(foo_baz=True) | models.Q(foo_bee=True) | models.Q(foo_boo=True)) # etc # ... So, I've found a dirty workaround. I filter all attributes of Lorem starting with foo_. # LoremQuerySet.foo() # ... foo_attrs = filter(lambda s: s.startswith("foo_"), dir(Lorem)) # filter attrs starting with "lorem_" # generator resulting in ("foo_bar", "foo_baz") etc # ... However, I'm stuck at this point. How can I … -
Settings error, when triggering a scraper from a django app?
Upon starting the script that converst json data and saves it to a model, i get this error. django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Anyone know how to fix this? pipelines.py holds the script that gives the error, located in the rest_models app folder. from django.conf import settings import pandas as pd import requests # import time # from .models import * import django django.setup() from models import Article settings.configure() def add_new_articles(): # class Command(BaseCommand): fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] fox = fox_articles.to_records() for article in fox: article = Article( article_author=article[1], article_title=article[2], article_description=article[3], article_url=article[4], article_urlToImage=article[5], article_content=article[6], article_network=article[7], article_date_publised=article[8], ) article.save() models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings class CustomUser(AbstractUser): fav_color = models.CharField(blank=True, max_length=120) class Article(models.Model): article_author = models.CharField(blank=True, max_length=1000) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.TextField(blank=True) article_description = models.TextField(blank=True) article_url = models.TextField(blank=True) article_urlToImage = models.TextField(blank=True) article_content = models.TextField(blank=True) article_network = models.CharField(blank=True, max_length=500) -
How can i use additional fields to get jwt token
i use https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ i have such code User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() ROLE_CHOICES = [ ('U', 'User'), ('M', 'Moderator'), ('A', 'Admin'), ] role = models.CharField(max_length=1, choices=ROLE_CHOICES, default='U') confirmation_code = models.CharField(max_length=30) And i want to get JWT token, here is my urls path("v1/token/", views.EmailTokenObtainPairView.as_view(), name="token_obtain_pair") i need send such POST query http://127.0.0.1:8000/api/v1/token/ with data : { 'email': email, 'confirmation_code': confirmation_code } but by default in simple-jwt i need to send data : {'username' : username, 'password':password } how can i change default way ? -
AttributeError from predicate in Django Admin when using django-rules
I am trying to create a first implementation with django-rules, following the guidelines in the README. To start with some basic concepts, I want to restrict deletion of a record to the record owner onlyin my app contact. I managed (it seems) to get things working with my API provided via Django REST Framework. However, when I open Django Admin with a non-superuser user, I get the following error: AttributeError: 'NoneType' object has no attribute 'created_by' This appears to be related to my predicate definition in contact/rules.py (I tried to follow the "book example" in the django-rules documentation here): import rules @rules.predicate def is_contact_owner(user, contact): return contact.created_by == user rules.add_perm("contact", rules.always_allow) rules.add_perm("contact.view_contact", rules.is_staff) rules.add_perm("contact.add_contact", rules.is_staff) rules.add_perm("contact.change_contact", rules.is_staff) rules.add_perm("contact.delete_contact", is_contact_owner) @rules.predicate def is_address_owner(user, address): return address.created_by == user rules.add_perm("address", rules.always_allow) rules.add_perm("address.view_address", rules.is_staff) rules.add_perm("address.add_address", rules.is_staff) rules.add_perm("address.change_address", rules.is_staff) rules.add_perm("address.delete_address", is_contact_owner) My contact/admin.py looks as follows: from django.contrib import admin from rules.contrib.admin import ObjectPermissionsModelAdmin # Register your models here. from .models import Address, Contact @admin.register(Address) class AddressAdmin(ObjectPermissionsModelAdmin): # class AddressAdmin(admin.ModelAdmin): list_display = ( "id", "local_address", "country", "uuid", "created", "modified", "created_by", "modified_by", ) date_hierarchy = "created" list_filter = ["created", "modified", "country"] @admin.register(Contact) class ContactAdmin(ObjectPermissionsModelAdmin): # class ContactAdmin(admin.ModelAdmin): list_display = ( "id", "last_name", "first_name", "date_of_birth", "uuid", … -
Facing Module Not Found Error while deploying Project in Heroku
I was trying to deploy my ecommerce website project from Heroku but I am facing this error: -----> $ 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 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_faec937d_/store/admin.py", line 2, in <module> from .models import * ModuleNotFoundError: No module named 'store.models' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets … -
Running celery beat on windows
I work on a Celery beat task within a django project which sends emails periodically. The worker is a RabbitMQ In a development environment I use the following commands to starting the Scheduler and worker process, respectively: celery -A proj beat --loglevel=info celery -A proj worker -- loglevel=info For the above I need to activate python virtual environment and run each command in separate CMD window and it worked perfectly. However, bringing it to a production environment (daemon) on Windows is not that easy. In this post Daemonising Celery on Windows launch Celery using a batch file and configure Windows Task Scheduler to run the Celery service periodically. Which seems to be a simple solution, although I don't know how advisable My question is, what would be the correct commands from the batch file to activate the virtual environment, execute the commands described in number 1) and 2) and finally stop the services. I know it is simple but I don't know what the correct commands are. If anyone can help me I would be very grateful. The following are the steps to activate the virtual environment, run celery beat and the worker and stop the process when it is … -
Is Django better or C# for website backend?
Well... I am working on a website and I am completely new to programming and Web-designing. I have made a website but it is only static for now and I want to implement a backend. I know Python quite well but I am new to C# and learning it. The problem or rather a question is that should I use Django(Python) for back-end development or should I wait and learn C# and then use C# as the back-end? I also had a thought of using PHP as my back-end, but I think Python would be more powerful. And I have read on Google that if I make the back-end in C# it will only run on Windows Server and not on Linux, Is it true? Thanks in Advance. -
Where is the result stored in Redis and how long will the result be stored before removed?
Currently, we are trying to figure out which plan we need to use for heroku-redis in our website. But before making any decision on that, We are trying to figure out how does the clients work in the redis. We've done some testing, and understand that clients are showing each commands that redis is calling; however, there are something we are still confused about and would be very appreciate if we could get some help on that! (If the timeout=0) It makes sense that every time when I refresh the website, the number of clients will be increased, most likely it is "get" and "unsubscribe" (even though other commands are being used, such as "subscribe" and "multi", etc. but they are not showing in the client list, which makes me a little confused since we set the timeout to 0, so it is supposed to be in the clients list, but it is not). However, when the number of "get" clients reach to 4 or 5 (depends), and when I start to refresh the page again, the number of "get" clients stopped increasing, and it seems redis is reusing it (I realized that because I see the idle time decrease … -
Using multiple admin.py files for Django rest?
I currently have 2 admin.py files. project/admin.py project/pages/basicpage/admin.py I would like to use the registered classes inside the second admin.py along with the first admin.py such that they can both be reached at the same admin endpoint. FILE ONE: project/admin.py from django.contrib import admin from project import models from project.pages.basicpage import admin as BP_admin @admin.register(models.Test) class TestAdmin(admin.ModelAdmin): pass FILE TWO: project/pages/basicpage/admin.py from django.contrib import admin from project import models @admin.register(models.Platform) class PlatformAdmin(admin.ModelAdmin): pass @admin.register(models.Type) class TypeAdmin(admin.ModelAdmin): pass In file one, I have imported the second admin as BP_admin, not that it is used yet. However when I access my http://127.0.0.1:8000/admin endpoint, understandably I only can view the "Test" class that is registered in the first file. Any idea how to get my other 2 classes from my second file registered to the first file's endpoint? Thanks! -
How to emulate Postgres Django distinct() with SQLite backend
I'm racking my brain on how to form this filter query using Django's Querysets. The following filter query returns objects containing the following fields: candidate, informationField, option. selected_options = CandidateInformationListOptionsAnswer.objects.filter( candidate=candidate, informationField=element ) In selected_option, every object will have the same values for candidate and informationField. However, the option fields in the objects in the QuerySet have duplicates, when they should be unique. Therefore, I want to run the equivalent of a .distinct("option") call on selected_options, but my DB backend is not Postgres, so I don't have the ability to pass in field names into a QuerySet.distinct() call. How would I structure my .filter() queries to get a QuerySet of objects that are distinct for a particular field with a SQLite backend? -
Merge duplicate values in django query
I have a SQL query but I want to know, how can I write in Django format (PostgreSQL). I'm new with django :) Suppose, we have data in a table like this. 1: Color: Pink, Size: 1M 2: Color: Pink, Size: 2M 3: Color: Red, Size: 1M 4: Color: Red, Size: 3M 5: Color: Yellow, Size: 2M Expecting output Pink Red Yellow I'm getting output with the below query. But I want to know, how can I query & merge duplicate values in django // id = product_id colors = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id=%s GROUP BY color_id',[id]) -
Retrieving multiple objects from Django REST API
I made a Django backend using the REST api using many-to-many relationships. I was wondering what is the best way to get all of the objects that a certain object is pointing to. So in my case there are decks that have cards, and the decks point to the cards' indexes. Cards can belong to multiple decks. What I do is retrieve all decks, then for a specific deck I will traverse a for loop for each card index, and call the api and retrieve the card and add it to a local array. I don't have any experience with backends before this, so I'm wondering how I could efficiently set up how my frontend calls the backend. I wrote my frontend using react-native, and make the calls with axios. -
Django Javascript Error: missing : after property id
I am getting this error when pressing the like button on my posts. It was working while showing the error for a while but now it won't work so where do i need to put the colon? full error: Uncaught SyntaxError: missing : after property id i have marked the where i think the error is pointing to(it's near the bottom) $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) var likeElement = document.getElementById(`like_button${post_id}`); var dislikeElement = document.getElementById(`dislike_button${post_id}`); var likeElementAd = document.getElementById(`like_button_ad${post_id}`); var dislikeElementAd = document.getElementById(`dislike_button_ad${post_id}`); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, }, success: function(response){ if (likeElement.classList.contains("liked_post")){ res = trimCount - 1 likeElement.classList.remove("liked_post") if (likeElementAd){ likeElementAd.classList.remove("liked_post") } } else if (!$(this).hasClass("liked_post")) { res = trimCount + 1 likeElement.classList.add("liked_post") dislikeElement.classList.remove("disliked_post") if (likeElementAd){ likeElementAd.classList.add("liked_post") } if (dislikeElementAd){ dislikeElementAd.classList.remove("disliked_post") } } $(`.like_count_ad${post_id}`).text(res +' Likes') $(`.like_count${post_id}`).text(res +' Likes') }, error: function(response){ console.log('error', response) } }) }) $('.dislike_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) var likeElement = document.getElementById(`like_button${post_id}`); var dislikeElement = document.getElementById(`dislike_button${post_id}`); var likeElementAd = document.getElementById(`like_button_ad${post_id}`); var dislikeElementAd = document.getElementById(`dislike_button_ad${post_id}`); $.ajax({ type: 'POST', url: … -
Django Celery Worker fetches old data
When I update a field on a Django model instance, save it, and try to fetch this model instance from within a celery worker then often it gives me the old value. If, however, I fetch the same model instance from outside a celery worker then I get the right value. For the database I use PostgresSQL. celery==3.1.25 Django==1.10.8 I know that the celery & Django version are outdated, but for this project it's currently not possible to bump it. Does anyone know what might be causing this behaviour? -
ForeignKey updates aren't cascading on Django created tables in Postgres
This is the error that I get when I try to update the value in the "parent" table that the foreign key is looking at in a related table: ERROR: update or delete on table "product" violates foreign key constraint "pd_family_product_guid_ada83db3_fk_product_guid" on table "pd_family" DETAIL: Key (guid)=(902d30b8-26ba-ea11-a812-000d3a5bbb60) is still referenced from table "pd_family". SQL state: 23503 This is what I have for my models: class Product(models.Model): guid = models.UUIDField(primary_key=True) product = models.CharField(max_length=10) year = models.IntegerField() previous_product_name = models.CharField(max_length=10) class StandardProductFieldsMixin(models.Model): product_guid = models.ForeignKey('Product', on_delete=models.CASCADE, db_column='product_guid') class Meta: abstract = True class ActiveFieldMixin(models.Model): active = models.BooleanField() class Meta: abstract = True class Family(StandardProductFieldsMixin, ActiveFieldMixin): new_code = models.IntegerField(null=True) code = models.DecimalField(max_digits=20, decimal_places=2) title = models.CharField(max_length=255) desc = models.TextField(null=True) fam_desc = models.TextField(null=True) When I try to change a value of guid in Product, my expectation is that it would automatically change it in Family as well. I guess I was under the wrong impression. Do I need to do something additional in the model? Looked at the documentation for something like on_update, but not seeing that either an **options or as a parameter for models.ForeignKey. -
How to add custom method in django forms
I am new to django, and I am creating a vacation application. I want to be able to when I create a new trip, the user that created the trip becomes a member of that trip. here is my models.py file: class Trip(models.Model): trip_name = models.CharField(max_length=255,unique=False) start_date = models.DateField(default=datetime.date.today) end_date = models.DateField(default=datetime.date.today) slug = models.SlugField(allow_unicode=True,unique=True) members = models.ManyToManyField(User,through='TripMember') def __str__(self): return self.trip_name def save(self,*args,**kwargs): self.slug = slugify(self.trip_name) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('trips:single',kwargs={'slug':self.slug}) class Meta: ordering = ['start_date'] class TripMember(models.Model): trip = models.ForeignKey(Trip,null=True,related_name='memberships',on_delete=models.SET_NULL) user = models.ForeignKey(User,null=True,related_name='user_trips',on_delete=models.SET_NULL) def __str__(self): return self.user.username class Meta: unique_together = ('trip','user') this is my forms.py file: class TripCreateForm(forms.ModelForm): class Meta: fields = ('trip_name','start_date','end_date') model = Trip def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["trip_name"].label = "Trip Name" self.fields["start_date"].label = "Start Date" self.fields["end_date"].label = "End Date" here is my views.py file: class CreateTrip(CreateView): form_class = TripCreateForm template_name = 'trips/trip_form.html' and my trip_form.html page: <form action="{% url 'trips:create' %}" method="post" id='tripForm'> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-primary btn-large" value="Create"> {% endblock %} Where would I put the code to set the user as a tripmember and why?Also, if there is a better way to have set this up please let me know! I was gonna … -
Setup the HstoreField type Django
I have need to store an Array inside my Django model. I heard about the ArrayField but I don't understand, how to install it. I don't see how I can install the Hstore extension needed in my Django project. Any help would be nice... I don't find any tutorials on this extension :/ Thanks -
Can the User model be overridden to make the email field required?
For my application, the email field in the Django User model should be required, but by default it's optional. I searched this question but most answers I found were talking about making the email field required in the customised UserCreationForm for example: class CustomUserForm(UserCreationForm): """Provide a view for creating users with only the requisite fields.""" class Meta: model = User # Note that password is taken care of for us by auth's UserCreationForm. fields = ('username', 'email') def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True but I want to make the email mandatory in the User model as well because I was thinking maybe ModelForm are a frontend thing and the required condition maybe be turned off by the user by using the chrome dev tools, am I wrong? Will making the email required in ModelForm is same as making it required in the user model as well, or can I override the user model to make the email required? -
Django Create Recurring Payments
Good day, I have two models, one for the destitute and the other for credit payments to be submitted to a bank for deposit into the destitute's acc. I need some guidance creating a function that loops through the Destitute table, creates recurring payments every month, and records them in the Credit table. Logic is if the destitute is above the age of 50 they get paid 2500k if below the age of 50 they get paid 2000k. If there is a Django package that can help achieve that would be great. class Destitute(models.Model): SEX_TYPE = (("male", "male"), ("female", "female")) name = models.CharField(max_length=100) acc_no = models.CharField(_("Bank Account"),max_length=50) age = models.PositiveIntegerField(default=1) sex = models.CharField( _("Transaction Source"), max_length=64, choices=SEX_TYPE) created_on = models.DateTimeField(_("Date Joined"), auto_now_add=True) def __str__(self): return self.name class Credit(models.Model): credit_title = models.CharField(_("Payment Title"), max_length=50) payee = models.ForeignKey( Destitute, related_name="destitute_paid", on_delete=models.SET_NULL, null=True, blank=True) total_amount = models.DecimalField( blank=True, null=True, max_digits=12) payment_date = models.DateField(blank=True, null=True) def __str__(self): return self.credit_title -
how to hide the value for the password field in Django Rest Framework API view
click here for the image in the attached image for the password field I need "****" instead of "pass", is there any password widget available for Serialzers? -
Django table rendering blank rows
I've searched far and wide, and haven't come up with a solution despite this probably being a simple fix. Models.py: class Leaderboard(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Score(models.Model): leaderboard = models.ForeignKey(Leaderboard, on_delete=models.CASCADE) player_name = models.CharField(max_length=25) score = models.IntegerField() time_set = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.player_name} - {self.leaderboard} [{self.score}]" views.py def index(response, name): # ls = Leaderboard.objects.get(name=name) sorted = Leaderboard.objects.filter(name=name).order_by('-score') return render(response, "highscores/leaderboard_ranks.html", {"ls": sorted}) And the relevant template part of the code. {% for item in ls %} <tr> <td></td> <td>{{item.player_name}}</td> <td>{{item.score}}</td> <td>{{item.time_set}}</td> </tr> {% endfor %} And this just outputs blank rows in the table. What am I missing?