Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get foreign key related JSON objects in Django template
So I currently have an API response that encodes a many-to-one relationship both ways, where the one object (called Sagas) has a set of the many objects (called Arcs) relating to it: //1 Saga contains many arcs in this way: //GET Saga [ { "id": 1, "arc_set": [ 1, 2, 3, 4, 5, 6 ], "name": "East Blue", "description": "The East Blue Saga is the introductory saga of the series...", "startChapter": 1, "endChapter": 100 }, ] //GET Arc [ { "id": 2, "name": "Orange Town", "description": "Luffy and his first crew member Zoro arrive at Orange Town where....", "startChapter": 8, "endChapter": 21, "saga": 1 }, ] basically I want to be able to go through the arc_set in my django template and grab the related arcs with the matching ids. It seems simple I'm just not too familiar with the django template syntax needed Currently all I've been working on is code to loop through the arc_set array and get the id values but I can't even get that to work, never mind getting the related Arc object: {% for saga in sagas|dictsort:'id' %} {% for arc_key, arc_id in saga.arc_set.items|dictsort:'id' %} but I've been unable to iterate through the arc_set … -
Creating Class Based ListView with form that submits
I am creating a Class Based ListView that contains a Form. I was able to add the form to my template but I am not able to submit the form. The submission should redirect to the original page. Here's the code: urls.py urlpatterns = [ path('<str:uuid_group>/manage/groupmembers', ManageGroupMembersListView.as_view(), name="manage_groupmembers"), ] forms.py class ManageGroupMemberForm(forms.ModelForm): class Meta: model = AadGroupmember fields = ['id_aaduser','id_aadpermissions'] views.py class ManageGroupMembersListView(ListView): model = PermissionAAD template_name = 'permissions/group_members.html' paginate_by = 10 def get_context_data(self, *args, **kwargs): context = super(ManageGroupMembersListView, self).get_context_data(*args, **kwargs) context['uuid_group'] = self.kwargs['uuid_group'] context ['object_list'] = self.model.objects.filter(Q(uuid__icontains=context['uuid_group'])) context['form'] = ManageGroupMemberForm() return context group_members.html <form method="post" action="{%url 'manage_groupmembers' uuid_group%}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> <table class="table"> <thead> <tr> <th scope="col">Users</th> <th scope="col">First Name</th> <th scope="col">test</th> </tr> </thead> <tbody> <tr> {% for user in object_list %} <td>{{ user.username}}</td> <td>{{ user.shortdesc}}</td> <td>{{ user.groupname}}</td> </tr> {% endfor %} </tbody> </table> -
Is it worth having social signup on my website?
I am creating a website and I've already implemented the "Sign up with Google" button and i've already added the normal user creation form. i'm considering adding the "Sign up with Facebook" button but I'm not sure if it's worth it. I couldn't find any reliable statistics online about social signup market share and I was wondering if anyone else knew. I am open to other ways of signing up as well. -
Django doesn't see model after migration
Just started to make a project, wrote code in models and decided to make migrations, after which I saw an error Operations to perform: Apply all migrations: socialaccount Running migrations: Applying socialaccount.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_advuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/src/auto_store/manage.py", line 22, in <module> main() File "/usr/src/auto_store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 251, in apply_migration migration_recorded = True File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 157, in __exit__ self.execute(sql) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 192, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, … -
launch Django project from any folder
In my project I use config file which is one level higher than manage.py. I use ConfigParser to read it, but for Django to run correctly I need to be in the directory where manage.py is Here is the part where the magic should happen import os import configparser # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config = configparser.ConfigParser() config.read('../config.ini', encoding='utf-8') and if i am in the right directory, everything launches correctly (.venv) kisha@LAPTOP-LLMM16ID:~/vmlist/vmlist_frontend/it$ ll total 388 drwxr-xr-x 13 kisha kisha 4096 Aug 5 16:05 ./ drwxr-xr-x 7 kisha kisha 4096 Aug 8 10:43 ../ drwxr-xr-x 6 kisha kisha 4096 Aug 5 16:05 accounts/ drwxr-xr-x 4 kisha kisha 4096 Aug 8 10:43 api/ drwxr-xr-x 7 kisha kisha 4096 Aug 5 16:05 cluster/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 description/ drwxr-xr-x 6 kisha kisha 4096 Aug 8 10:43 direction/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 errors/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 graphs/ drwxr-xr-x 6 kisha kisha 4096 Aug 5 16:05 it/ -rw-r--r-- 1 kisha kisha 622 Jun 29 15:07 manage.py drwxr-xr-x 2 kisha kisha 4096 Aug 2 11:47 migrations/ -rw-r--r-- 1 kisha kisha 17976 Aug 8 10:36 request.log … -
sqLite3.ProgrammingError when trying to run python manage.py dumpdata
I am trying to run python manage.py dumpdata > data.json and it's giving me this error. CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-8: character maps to Exception ignored in: <generator object cursor_iter at 0x0000029AAC7E9E00> Traceback (most recent call last): File "C:\Users\jsalv\Desktop\ItPartsECommerce\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1876, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. The code that is throwing the error is the following: def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close() The error comes out but the file gets generated, when it does it's never full, the last lines do not close out and because of that I cannot migrate my database to PostgreSQL, I tried saving this file with UTF-8 decode but it didn't work. Can anyone tell me if I'm doing something wrong? -
Using prefetch_related to reduce expensive query
How can i make the querying here on the database level. in my code for assigning the emails to the list i am using python code instead i want to make use of ORM querying i.e on the database level how can my query look like here. models.py class UserModel(models.Model): email = models.EmailField(unique=True, blank=True, null=True) class Mymodel(models.Model): name = models.CharField(max_length=300) assignees = models.ManyToManyField( User, related_name='tasks', blank=True, ) send_email = models.BooleanField(default=False) views.py def my_view(self): due_date = datetime.date.today() records = Mymodel.objects.filter(due_date=due_date) for rec in records: if rec.send_email: responsible_emails = [] for person in rec.assignees.all(): responsible_emails.append(person.email) -
Django detect model changes at runtime
I'm trying to generate migration files dynamically to detect changes in the model, but the issue is, makemigration command only create the migration file once and after that it says no changes detected.I tried, removing the app dynamically, and then adding it back, but that didn't work either. I have shared my code with you, any help would be appreciated, thanks. from collections import OrderedDict from django.apps import apps from django.core.management import call_command import os import shutil def add_dynamic_app(app_name, db_name='default', backwards=False): if app_name not in settings.INSTALLED_APPS: app_path = os.path.join(settings.BASE_DIR, app_name) os.mkdir(app_path) with open(os.path.join(app_path, "__init__.py"), "w") as f: f.write("") with open(os.path.join(app_path, "apps.py"), "w") as f: f.write( f""" from django.apps import AppConfig class {app_name.title()}Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = '{app_name}' """ ) with open(os.path.join(app_path, "models.py"), "w") as f: f.write( f""" from django.db import models class DynamicModel(models.Model): class Meta: app_label = '{app_name}' db_table = 'dynamictable' phone = models.CharField(max_length=13) name = models.CharField(max_length=50) """ ) ## Dynamic App Loading new_app_name = app_name settings.INSTALLED_APPS += (new_app_name, ) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) ## Dynamic Migration and SQL Creattion migration_name_1 = "dynamic_migration" args = ["sqlmigrate", app_name, f"0001_{migration_name_1}"] if db_name: args.extend(['--database', db_name]) if backwards: args.extend(['--backwards']) call_command("makemigrations", "--name", migration_name_1, app_name, … -
I am having issue with getting the source of streaming video with django
I had issue the video tag on chrome because I want to be able to skip to particular time on the video, google chrome does not allow that to happen because it requires a specific kind of response after doing some research I came to this post on stackoverflow after adding the code, I set the endpoint on the source tag of the video like this <source src="{% url 'namespace:stream_video' obj.video.path %}" type="video/mp4" /> even did it like this <source src="{% url 'namespace:stream_video' path=obj.video.path %}" type="video/mp4" /> But I am getting NoReversMatch 'stream_video' with arguments '('/home/UserName/Work/projectName/media/uploads/2022/8/3/b3f10ea2-b323-4398-a86c-c5fb5936cfd723.mp4',)' not found. 1 pattern(s) tried: ['video\\-stream/(?P<path>[^/]+)\\Z'] The path path("stream/<str:path>", views.stream_video, name="stream_video") And this is my view it's literally a copy of the view from the post: def stream_video(request, path): range_header = request.META.get('HTTP_RANGE', '').strip() range_match = range_re.match(range_header) size = os.path.getsize(path) content_type, encoding = mimetypes.guess_type(path) content_type = content_type or 'application/octet-stream' if range_match: first_byte, last_byte = range_match.groups() first_byte = int(first_byte) if first_byte else 0 last_byte = int(last_byte) if last_byte else size - 1 if last_byte >= size: last_byte = size - 1 length = last_byte - first_byte + 1 resp = StreamingHttpResponse(RangeFileWrapper(open(path, 'rb'), offset=first_byte, length=length), status=206, content_type=content_type) resp['Content-Length'] = str(length) resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, … -
How to set CustomUser’s field value inside APIView?
I have a custom user model with a tokens Integerfield and an APIView that sends a request to OpenAI’s GPT-3 API. I want to implement a feature where user has a token limit. When user has less than 0 tokens left as their user field, the GPT3 APIView will respond with a 400BADREQUEST. The GPT-3 API returns how many tokens an user has used in a single request, so I wanted to “SET” this user’s tokens field inside the APIView like the following: request.user.tokens = request.user.tokens - used_tokens # This line does not work It doesn’t give any error, but the user’s tokens field is never updated. Anyone has idea how to accomplish this? users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) tokens = models.IntegerField(default=200) appname/views.py class GPT3(ApiPremiumMixin, APIView): def post(self, request, format=None): try: response = requests.post( url="https://api.openai.com/v1/completions", headers={ "Authorization": "Bearer " + os.getenv("GPT3_API_KEY"), "Content-Type": "application/json; charset=utf-8", }, data=json.dumps(request.data), ) used_tokens = response.json()["usage"]["total_tokens"] print(request.user.tokens) request.user.tokens = request.user.tokens - used_tokens # This line does not work print(request.user.tokens) return JsonResponse( response.content.decode("utf8"), status=status.HTTP_200_OK, safe=False ) except requests.exceptions.RequestException: Response("Request Failed", status=status.HTTP_400_BAD_REQUEST) -
Django inlines without Foreign Key
I have models: class MyModel(models.Model): name = models.CharField() group = models.ForeignKey(Group) class Group(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() group = models.ForeignKey(Group) I want to get inlines (City) in the admin of MyModel for a group that includes cities: class CityInline(admin.TabularInline): model = City @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('pk', 'name',) inlines = [CityInline, ] How can I do this? -
django.db.utils.IntegrityError: null value in column "auto_id" of relation "university_university" violates not-null constraint
Iam getting a integrity error, i have tried adding null=True to auto id field then its working but auto_id field must not be blank=True or null=True.These models are given by my superiors i am finding this hard to understand This is the core app models.py import uuid from django.db import models from django.db.models import Max from django.utils import timezone from decimal import Decimal from django.utils.translation import gettext_lazy as _ from django.core.validators import MinValueValidator from core.utils import DictField from django.contrib.auth import get_user_model from django.contrib.humanize.templatetags.humanize import naturaltime def basedata(self, request): # Check is create if self._state.adding: self.auto_id = (self.__class__.objects.aggregate(max_auto_id=Max('auto_id')).get('max_auto_id') or 0) + 1 if request.user.is_authenticated: self.creator = request.user # If updating if request.user.is_authenticated: self.updater = request.user self.date_updated = timezone.now() class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_id = models.PositiveIntegerField(db_index=True, unique=True) creator = models.ForeignKey(get_user_model(), blank=True, related_name="creator_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE) updater = models.ForeignKey(get_user_model(), blank=True, related_name="updater_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE) date_added = models.DateTimeField(db_index=True, auto_now_add=True) date_updated = models.DateTimeField(auto_now_add=True) is_deleted = models.BooleanField(default=False) class Meta: abstract = True def delete(self): self.is_deleted = True self.save() def delete_with_user(self, user): self.is_deleted = True user = self.user user.username = user.username + '_deleted_' + str(self.id) user.save() self.save() @property def date_added_natural(self): return naturaltime(self.date_added) class Mode(models.Model): readonly = models.BooleanField(default=False) maintenance = models.BooleanField(default=False) down = models.BooleanField(default=False) class … -
Can somebody tell me about this slash in path?
Can somebody tell me the difference between two paths? This is my urls.py in django urlpatterns = [ path('update/<int:id>/', views.update), ] urlpatterns = [ path('update/<int:id>', views.update), ] <form action="/app/update/{id}/" method="POST"> Why I should add slash(/) in the end of path? If I add / in path in urlpatterns, when I submit , it works well. If I don't, it occurs an error. -
Django + JS-Framework vs Django + native Javascript
I'm currently developing a website with a friend (Django + Django Templates with Bootstrap). It started as a learning project so we altered a lot during the development process. The project has around 30K to 40K lines of code and we tried a rather component based approach by including often used code fragments from external files with the django template language. By now, even if it started out as a learning project, we want to take it online when it's finished so it's supposed to handle mid to high web traffic in production. The question we're asking ourselves now is if it's worth migrating to a JS-Framework like Svelte or React since we'd like the website to be as fast as possible and we'd like to migrate it into a SPA. Would there be a benefit in using a framework like Svelte for realizing such goals or would this approach also be a suitable option for us? -
Multiple proxy_pass destination for multiple domain name
What I want to do is like this, Change the destination of proxy depending on domain name. However it shows the error a duplicate default server for 0.0.0.0:8090 in /etc/nginx/sites-enabled/default:7 server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name exmaple.com; location / { proxy_pass http://127.0.0.1:8021/; include /var/www/html/exmaple/current/uwsgi_params; } } server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name exmaple2.com; location / { proxy_pass http://127.0.0.1:8022/; include /var/www/html/exmaple2/current/uwsgi_params; } } I should not duplicate the server delective. However how can I use multiple proxy_pass. -
Prevent repetition code in methods get and post in django class vase view
Prevent repetition code in methods get and post in django class vase view There are several lines of code in the get method that are also used in the post method. How can I prevent repeating codes in this view? What method should I use to prevent codes? class ProductDetail(View): def get(self, request, *args, **kwargs): products = Product.objects.get(id=self.kwargs['pk']) related_products = products.tags.similar_objects()[:4] comments = Comment.objects.filter(is_reply=False, product_id=self.kwargs['pk']) change = Chart.objects.filter(product_id=self.kwargs['pk']) context = ( {'products': products, 'related_products': related_products, 'comments': comments, 'change': change}) return render(request, 'home/details.html', context) def post(self, request, *args, **kwargs): products = Product.objects.get(id=self.kwargs['pk']) related_products = products.tags.similar_objects()[:4] comments = Comment.objects.filter(is_reply=False, product_id=self.kwargs['pk']) change = Chart.objects.filter(product_id=self.kwargs['pk']) context = ({'products': products, 'related_products': related_products, 'comments': comments, 'change': change}) return render(request, 'home/details.html', context) -
Finding the Position of a certain record in the Query in DJango ORM
I have a model of Django like this, class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) ratings = models.FloatField(default=1000) What I want to do is the person who's logged in, I want to find his rank based upon the user's ratings. So, that is, I need to find the Position of the specified row in a query where the records will be ordered by the ratings column, in descending order. I found a good solution here but it is unfortunately not working for me. https://stackoverflow.com/a/51317266/11454905 Using this same concept, I typed this query, player = Account.objects.filter(user = request.user).annotate(rank = Window(expression=Rank(), order_by=F('ratings').desc()),)[0] But no matter what user is, it always returns player.rank as 1, which is not true. I fail to understand what am I doing wrong and how can I correct it. -
Django S3 private storage
Users in my django project can upload pdf files to a private storage. It is done using django-private-storage package - when user makes a request to get a file, django checks permissions on that and then adds x-sendfile header so apache would serve the file. Now I am trying to move all that to S3 storage. I can't seem to understand how to do that. Most info that I found on the internet is telling me to put private files in a private bucket and then serve expiring links. I don't like the expiring links and I don't want to expose any S3 links. One-shot links would be fine, maybe. Is there any way to serve files without exposing any direct S3 links and without using expiring links? Am I missing something? -
How to save separated values from a list of numbers
i want to recibe a list of values(numbers in this case) in a key called "sensor_data" and save those values separated but i couldnt figureout how to make this function without using another framework. @api_view(['POST']) def saveData(request): values_list = [] separated_values = values_list.split(',') sensor_data = {'sensor_data' : values_list } print (sensor_data) return Response() -
How to get last six month report django (even in between months not having entry)
I wanted to get last six months of employee count by checking joining_date field class Employee(models.Model): employee_name = models.CharField(max_length=100) joining_Date = models.DateField(blank=False, null=False) Example: July : 12, June : 10, May : 8, April : 16, March : 13, February : 10, I got an answer for that from 0svoid, check here Its really working great! but problem is when there is no entry in particular month I want it to be 0 instead of not coming in the list. Say for example june month not having any employee joining. it should show like July : 12, June : 0, May : 8, April : 16, March : 13, February : 10, instead of below one. July : 12, May : 8, April : 16, March : 13, February : 10, I want to work on many scenario(s) something like above , please suggest me any module or a way to generate reports to show in the template from the database(s).. -
Django and AmqpConsumer with another apps
I have django apps and amqp consumer/publisher. I want to send an incoming message to my function in another application. But I get error messange: 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.' how can I do this? My settings.INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app', 'rabbit_client.config.AmqpConfig' ] AmqpConfig: from django.apps import AppConfig from rabbit_client.amqp_client import AMQPConsuming class AmqpConfig(AppConfig): name = 'rabbit_client' def ready(self): consumer = AMQPConsuming() consumer.daemon = True consumer.start() AMQPConsuming: import threading import pika from django.conf import settings from my_app.util import my_function # it's call error messange class AMQPConsuming(threading.Thread): def callback(self, channel, method, properties, body): data = body my_function(data) @staticmethod def _get_connection(): parameters = pika.URLParameters(settings.RABBITMQ_SETTING['URL']) return pika.BlockingConnection(parameters) def run(self): connection = self._get_connection() channel = connection.channel() channel.queue_declare( queue=settings.RABBITMQ_SETTING['QUEUE_CONSUME'], durable=True ) channel.basic_qos(prefetch_count=1) channel.basic_consume( on_message_callback=self.callback, queue=settings.RABBITMQ_SETTING['QUEUE_CONSUME'] ) channel.start_consuming() -
POST and models not matching - causing MultiValueDictKeyError
I inserted new model fields into my existing model in Django yesterday. This is how it looks: Then I ran these two commands- python manage.py makemigrations python manage.py migrate In my views.py I try to get from the post request all the added fields, but it gives me this error: When I look into the POST itself I see that none of my new fields were added! I understand that the fields are non-exsistent in the new request.POST, so the error pops in this part of the code: def updaterecord(request, id): group_name = request.POST['group'] sale_rent = request.POST['sale_rent'] street = request.POST['street'] city = request.POST['city'] rooms = request.POST['rooms'] size = request.POST['size'] floor = request.POST['floor'] porch = request.POST['porch'] storage = request.POST['storage'] mamad = request.POST['mamad'] elevator = request.POST['elevator'] parking = request.POST['parking'] price= request.POST['price'] phone= request.POST['phone'] date = request.POST['user_date'] I just don't understand how to solve this, is there any updates or commands I need to make? I don't remember how I solved it last time or how to avoid it in the future. Help please :-) -
Huey running task multiple times
I have a Huey task on a Django app that sends emails. The task runs every morning at 9am and is meant to send an email to certain customers. The task runs successfully, but runs again and again rather than just once, sending about 20 emails to each customer. @db_periodic_task(crontab(hour='9')) @lock_task('task-lock') def email_task(): emails_to_send = Customer.objects.filter(email_to_send=True) for customer in emails_to_send: send_email(customer) mark_email_to_send_false(customer) return True I've added a bool flag to the query and tried locking the task, but it keeps running multiple times. How do I make it just run once? -
Django project file is not showing
I created a my world project file in django and it’s not visible in the server. The response I get from my terminal is [Errno2 ] no such file or directory -
How to add html data attribute in django charfield?
I have following code in model password = models.CharField( max_length=32, null=True, blank=True, verbose_name="Code for downloaded Zip" ) I'm using admin to modify data, I want to add data-lpignore="true" attribute when django-admin displays form. I have added following code when I register model to admin which does not seems to work formfield_overrides = { models.CharField: {"widget": forms.TextInput(attrs={"data-lpignore": "True"})}, } Any ideas about how to add this data attribute in my model itself?