Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem setting my python/django project up in docker
I am having a problem setting my python/django project up in docker. I ran docker build . and it ran OK to the end with no errors. My source code is in my Z: drive is /ISICSFLSYN01/ISICSFLSYN01 which is my synology NAS. When I run the docker-compose.yml, I get the following message "mount path must be absolute". How do I get docker-compose to see the code in my NAS? docker-compose.yml version: "3.9" services: web: build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code" running Z:\Django Projects\code>docker-compose up [+] Running 0/0 Container 7bc5f2ff15b2_7bc5f2ff15b2_7bc5f2ff15b2_code-web-1 Recreate 0.1s Error response from daemon: invalid volume specification: '/run/desktop/mnt/host/uC/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code":rw': invalid mount config for type "bind": invalid mount path: '"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code"' mount path must be absolute Z:\Django Projects\code> My directories are set up: Z:\Django Projects\code> .venv .vs django_project pages .dockerignore db.sqlite3 docker-compose.yml dockerfile manage.py requirements.txt -
Heroku application error whentrying to deploy django project
i'm trying to deploy my django project on heroku. The deployment is successful but then if I try to go to my project page I get the following error: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail This is my deployment log: -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.10.7 -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 130 static files copied to '/tmp/build_fe9a8caa/staticfiles', 384 post-processed. -----> Discovering process types Procfile declares types -> realease, web -----> Compressing... Done: 29.5M -----> Launching... Released v4 https://appname.herokuapp.com/ deployed to Heroku -
Django DISTINCT and get all the objects from the distinct value
Can someone here help me with this problems ? struggling so long and can't get it right. Suppose I have this database: id Referall Code User Email Date of Using ______________________________________________________________________ 1 ABCD John john@email.com 13-06-2022 2 EFGH Marry marry@email.com 17-06-2022 3 IJKL Bryan bryan@email.com 21-06-2022 4 ABCD Luke luke@email.com 05-07-2022 5 EFGH Tom tom@email.com 11-08-2022 What I want the result will be like this: Referall Code User Email Date of Using _______________________________________________________________ ABCD John john@email.com 13-06-2022 Luke luke@email.com 05-07-2022 EFGH Marry marry@email.com 17-06-2022 Tom tom@email.com 11-08-2022 IJKL Bryan bryan@email.com 21-06-2022 I am using sqLite as a database, and can't find a way to get it done in django. Thanks in advanced -
How to make it so that when saving data in the database, the data generated by the function is automatically inserted into the field Django ORM
I'm writing a site on Django and ran into a problem I have a title field in the database, which stores the title of the book, but I want to add a chunk_title field, which will store the title of the book, divided into chunks of 3 characters, I wrote a method that does this, but I need that when inserted into the database, it was automatically applied and its result was inserted into chunk_title This is my DB model,where the last field is the field I want to auto-generate the value into: class Book(models.Model): """ Клас,який зберігає всі книги на сайті """ title = models.CharField(max_length=120, default=' ', verbose_name='Назва') description = models.TextField(verbose_name='Опис') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категорія') date_at = models.DateField(auto_now_add=True, verbose_name='Дата створення') image = models.ImageField(upload_to='photos/%Y/%m/%d/') authors = models.ManyToManyField(Author, verbose_name='Автори') content = models.FileField(upload_to='contents/%Y/%m/%d/', blank=True) price = models.IntegerField(verbose_name='Ціна', default='0') chunk_title_book = models.TextField(default=' ') And this is my method, the result of which I want to insert into that field (it is in the same class, i.e. Book): def chunk_title(self, string: str) -> str: """ Розбиває назву книги на чанки по 3 символи макисмум для подальшого пошуку по цих чанках """ chunk_string = ' '.join(textwrap.wrap(string, 3)) return chunk_string + ' ' + ' … -
Django channels - disconnect WebSocket from server side when token expires or gets invalid
I searched about this topic, specifically for Django, but i did not find any applicable solution. Namely, when i use a JWT as a query parameter to authenticate the user while opening a socket connection, the problem i'm thinking of is that the connection can be open for a long time which can exceed the validity of the token. The token can expire or even get invalid if some data changes. If someone steals the token which is expired, he can't really do anything with it because he cannot establish a new socket connection, so i assume this is not a big deal (maybe i'm wrong). The validity of the token on the data side is a bit different. If i used a data part to define the channel name, and then exactly that information changes, the old socket connection will receive the old data even when it should not. For example, if i used users company name for the channel name, and then the admin changes users company, while the old socket connection is still open, the user will still receive data from the old company until the old connection is disconnected and new one established. So i would … -
Django template priority operator
I have a condition {% if AAA or BBB and CCC %} do something {% endif %} Is it possible to do the OR first ? I try {% if (AAA or BBB) and CCC %} do something {% endif %} But it doesn't work Could not parse some characters: ( -
log messages from django application not uploaded in aws watch
I have added log messages in my django application and it was successfully logging log messages to the log file. Now, I tried to add log messages to aws cloud watch. When I run the application it creates log group in aws cloud watch but log stream is not created and log messages also not uploaded. I have also manually created log stream in aws cloud watch but still log messages were not uploaded. I have the following logging configuration in my django application. logger_boto3_client = boto3.client( "logs", aws_access_key_id=CLOUDWATCH_AWS_ID, aws_secret_access_key=CLOUDWATCH_AWS_KEY, region_name=AWS_DEFAULT_REGION, ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': "[cid: %(cid)s] [%(asctime)s.%(msecs)03d] %(levelname)s [%(name)s:%(lineno)s] [%(funcName)s] %(message)s", 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'logger': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': str(BASE_DIR) + '/logs/test.log', 'formatter': 'simple', 'filters': ['correlation'], }, 'watchtower': { "level": "DEBUG", "class": "watchtower.CloudWatchLogHandler", "boto3_client": logger_boto3_client, "log_group": "DemoLogs2", # Different stream for each environment "stream_name": "logs", "formatter": "simple", 'filters': ['correlation'], } }, 'filters': { 'correlation': { '()': 'cid.log.CidContextFilter' }, }, 'loggers': { 'root': { 'handlers': ['logger', 'watchtower'], 'level': 'DEBUG', 'filters': ['correlation'], 'propagate': True, } } } In my application I'm using logger like this, import logging logger = logging.getLogger(__name__) logger.info("log message.") My aws cloudwatch console. -
pass an ID to serializers.RelatedField djagno rest framework (DRF)
i have this code here : class TradePartsSerializer(serializers.ModelSerializer): class Meta: model = TradePart fields = '__all__' class TradeSerializer(serializers.ModelSerializer): tradepart = serializers.RelatedField(many=True, queryset=TradePart.objects.filter(TRADE ID)) class Meta: model = Trade fields = ['user', 'partsNum', 'tradepart'] how i can pass the trade ID from TradeSerializer to queryset=TradePart.objects.filter(TRADE ID HERE!) so i can return trade parts for each trade my views.py: if 'user' in request.query_params: userId = request.query_params['user'] user = User.objects.get(id=userId) trades = Trade.objects.filter(user=user) serializer = TradeSerializer(trades, many=True) return Response({'trades': serializer.data}, status=200) -
Utilizar "range" en filterset_fields de django-filters en DRF
estoy intentando traer un rango de un valor y no encuentro ejemplos de como usarlo en la consulta por postman. Por otro lado para probar que el campo funciona para la búsqueda hice una consulta con "exact" y tampoco me esta tomando el campo, por lo que pienso que en realidad el inconveniente está en el campo que llamo. Si bien este campo esta en el modelo, el valor del mismo lo obtengo des un método en el serializer. Como podría yo filtrar por este campo si el valor lo obtengo recién en la respuesta? paso el filtro en la view y el serializer ** filtrar por este campo** filterset_fields = { 'ppv': ['range'] } **campo en el serializer** ppv = serializers.SerializerMethodField(read_only=True) -
customize url on django
I would like to set up a url path that takes into account any string consisting of ASCII letters or numbers, the hyphen or character and also a period. For example: localhost:8000/mysite/toto-25b.ko How to set this up with re_path ? -
can i stop repetition of tags after each post?
The same tags are being repeated and displayed in the dropdown list. It is looping over the tags used in each post but it is not checking if the tags are repated or not. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> views.py def home(request, tag_slug=None): posts = Post.objects.all() #tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) return render(request, 'blog/home.html', {'posts':posts}) models has class Post(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) tags = TaggableManager() def __str__(self): return self.title urls.py has path('tag/<slug:tag_slug>/',views.home, name='post_tag'), I wanna use the same tag in different posts. Like when blogs are posted where it may use the same tag I am using Django-taggit -
Using filters through the django-filter module
Please tell me what am I missing. It is necessary to implement a table search in several columns as in the screenshot.[enter image description here][1] [1]: https://i.stack.imgur.com/1Zzw1.png. There is a video on YouTube with the implementation, but through the functions. <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{tableFilter.form}} <button class="btn btn-primary" type="submit"> Поиск </button> </form> </div> </div> </div> views.py class Home(ListView): model = Reports template_name = 'gaz_app/index.html' context_object_name = 'Reports' paginate_by = 20 def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'ИС' return context def seacrh_filter(request): customer = Reports.objects.all() orders = Reports.order_set.all() context = {'orders': orders} tableFilter = OrderFilter(queryset=orders) orders = tableFilter.qs return render(request, 'gaz_app/index.html', context) filters.py class OrderFilter(django_filters.FilterSet): # минимум 2 атрибута class Meta: model = Reports # Модель для которой мы создаем фильтр fields = ['facility', 'structural_unit'] # Указываем какие поля мы хотим разрешить urls.py urlpatterns = [ path('', Home.as_view(), name='home'), path('structural_unit/<str:pk>/', ReportByStructuralUnit.as_view(), name='structural_unit'), path('report/<str:pk>/', GetReport.as_view(), name='report'), ] models.py class Reports(models.Model): """Отчеты""" short_title = models.CharField(max_length=150, verbose_name='Краткое название') comment = models.TextField(blank=True, verbose_name='Комментарий') facility = models.ForeignKey('Facility', on_delete=models.PROTECT, verbose_name='Объект') structural_unit = models.ForeignKey('StructuralUnit', on_delete=models.PROTECT, verbose_name='Структурное подразделение') executor = models.ForeignKey('Executor', on_delete=models.PROTECT, verbose_name='Исполнитель') surveys = models.ForeignKey('Surveys', on_delete=models.PROTECT, verbose_name='Вид исследования') file = models.FileField(upload_to='Отчеты объектов', verbose_name='Отчет для загрузки') year_of_work = models.DateField(verbose_name='Отчетный период') … -
User input error 405 Method Not Allowed (POST)
I'm stuck with Django form. I would like to have an input field on my DetailView page, that takes player score. Then I want to process this score in pythton function, but every time i get error 405 Method Not Allowed (POST) html: <h7><img style="width:2rem; height:2rem" src="{{ player.avatar.url }}"> {{player}}</h7> <form method="POST"> {% csrf_token %} <input style = "width:2rem" type="text" id="{{player}}" name="score"> <input type="submit" name="score" value="OK"> </form> {{ val }} Form: class GetScoreForm(Form): score = CharField() views def get_score(request): if request.method == 'POST': form = GetScoreForm(request.POST) if form.is_valid(): val = form.cleaned_data.get("score") # HERE I WANT TO PROCESS MY SCORE else: form = GetScoreForm() return render(request, 'tournamentdetailview.html', {'form': form}) ``` -
AbstractBaseUser - creating a model leads to Field 'id' expected a number but got string?
I am trying to create a custom User model: When I hit the end-point to register a user I get the following error: Traceback (most recent call last): File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/db/models/fields/init.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'hashtag' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/xxx/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Volumes/coding/user_django/accounts/api.py", line 25, in post serializer.save() File "/Users/xxx/eb-virt/lib/python3.8/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/Volumes/coding/user_django/accounts/serializers.py", line 38, in create user = User.objects.create_user(username=validated_data['username'], File "/Volumes/coding/user_django/accounts/models.py", line 18, in create_user user.save() File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 68, in save super().save(*args, **kwargs) File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/Users/xxx/eb-virt/lib/python3.8/site-packages/django/db/models/base.py", line 970, in _save_table updated = self._do_update( … -
Django ORM order by the in operator list
the title explains it all. I need to filter my model for all elements of a list. Event.objects.filter(name__in=d) how can i sort the result according to the order of the elements of list d? I tried with [e for t in d for e in events if e.name == t] but it is really slow. is there what other faster option? -
Send messages asynchronously using Django Channels as they are generated
I've a process that receives data asynchronously using httpx, and I would like to send this data as soon as it is received. Instead Channels only sends it once all the data is received. Not sure if there is something basic I've misunderstood but I'd have thought this would be bread and butter functionality for an asynchronous framework. I'm using channels in memory layer, and don't have the option to install Redis server, besides based on other questions on stackoverflow - I'm not sure if that would help anyways. Minimal example: class AsyncSend(AsyncJsonWebsocketConsumer): async def connect(self): # Join group self.group_name = f"test" await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() #Replicate non blocking call async for result in self.non_block(): await self.send_task(result) async def non_block(self): for integer in range(4): await asyncio.sleep(1) curTime = datetime.now().strftime("%H:%M:%S") print(f"{curTime} - {integer}") yield integer async def send_task(self, result): curTime = datetime.now().strftime("%H:%M:%S") print(f"{curTime} - Send task called") await self.channel_layer.group_send( self.group_name, { 'type': "transmit", 'message': result, } ) print("Finished sending") async def transmit(self, event): print(f"Received event to transmit...") async def disconnect(self, close_code): # Leave group await self.channel_layer.group_discard( self.group_name, self.channel_name ) Output: 10:23:21 - 0 10:23:21 - Send task called Finished sending 10:23:22 - 1 10:23:22 - Send task called … -
Django select2 does not appear
I try to add the Select2 in my django app but i can't use it. When I click on the box to perform the search does not appear so it does not work. Does anyone have a solution so that i can use it in my app ? ======== Page.html ======== {% load static %} <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <title>THE PAGE</title> </head> <link rel="icon" type="image/x-icon" href="{% static 'images/icons10.png' %}"> <body> {% include 'accounts/navbar.html' %} <div class="container-fluid"> {% block content %} {% endblock %} </div> <hr> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- Select2 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"> </script> <script> $(document).ready(function() { $('#id_employe').select2(); }); </script> <!-- Footer --> <footer class="page-footer font-small blue"> <!-- Copyright --> <div class="footer-copyright text-center py-3">© {% now "Y" %} <h7>PAGE</h7> </div> </footer> <!-- Footer --> </body> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </html> This is the page of the form. ============ The page of form.html ========= {% extends 'accounts/page.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <br> <h3>ADD … -
Upload to Heroku - ProgrammingError: relation does not exist
I deployed my application to Heroku, but I am not able to add any data. When I tried to open first table with data from model I received this error message: ProgrammingError at /category/category_table relation "tables_category" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "tables_category" And when I tried to add first data I received this error message: ProgrammingError at /admin/tables/category/add/ relation "tables_category" does not exist LINE 1: INSERT INTO "tables_category" ("category_name") VALUES ('sho... I went through similar Q/A here, but they do not solve my issue, as I have: a) deleted all migration files from my local disk, then b) I run: python3 manage.py makemigrations c) I run: heroku run python3 manage.py migrate So all should be up to date and I have this log from Heroku: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, tables Running migrations: No migrations to apply. So currently do not know what to do. Maybe the problem is that I completely deleted file with migrations, because now I tried to change one my model and when I tried makemigrations and migrate, answer was no migrations to apply. So I copied file __init__.py to migrations file and no makemigration is … -
How to navigate through multiple pages from search in Django?
I am trying to create a webpage using Django where my database consists thousands of CVEs and display the list of CVEs based on what I typed in the search bar. So far, the search function is working perfectly and it displays the paginated results. But when I try to navigate to next page, it will show a blank page. Below is the code of my views.py and template. views.py def search_cve(request): if request.method == 'GET': searched = request.GET.get('searched') if searched: cve_search = BDSA.objects.filter(cve_id__icontains=searched) paginator = Paginator(cve_search.order_by('-cve_id'), 10) # show 10 per page try: page = int(request.GET.get('page', '1')) except: page = 1 try: cves = paginator.page(page) except: cves = paginator.page(1) index = cves.number - 1 max_index = len(paginator.page_range) start_index = index - 2 if index >= 2 else 0 end_index = index + 2 if index <= max_index - 2 else max_index page_range = list(paginator.page_range)[start_index:end_index] return render(request, 'QueryService/search_cve.html', {'searched':searched, 'cve_search':cve_search, 'cves': cves, 'page_range': page_range}) else: return render(request, 'QueryService/search_cve.html', {}) template <body> {% block content %} <br/> <center> <h1>Searched for: {{ searched }}</h1> <br/> <div class="container"> <table class="table table-hover table-striped table-bordered"> {% for cve in cves %} <tr> <td><a href="{% url 'show-cve' cve.cve_id %}">{{ cve }}</a></td> </tr> {% endfor %} </table> … -
How to setup multiple django projects to access the same database and models
I have one django project that serves as an API and contains a database and multiple apps with models, database migrations and so on. I want to have a custom admin interface as well as django-admin which are only accessible via the intranet. Is this possible within the same django project while the other apps are accessible from outside the intranet? And if not, is it possible to have two django projects. One which serves as the API containing the database, models and migrations. And another one that contains just the django-admin and my custom admin interface app that can access the databse and models from the other project? -
Getting anonymous user after login through otp
I am trying to authenticate the user through only otp and without password. After user enters his/her email, an otp will be sent to that email. After login, the user has several page links to go to and I want that user to stay logged in for those pages. The homepage after login is receiving the user details but not after the user goes to any other page. For eg., if the user clicks on Add Owner after logging in, request.user returns AnonmousUser. models.py class S_Society_Association_Master(models.Model): society = models.ForeignKey(S_Society_Master, default=0, on_delete=models.CASCADE) member_name = models.CharField(verbose_name = "Member Name", max_length=100) member_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) otp = models.CharField(max_length=6, blank=False, default=0) # For HOTP Verification member_role = models.CharField(verbose_name="Member's Role", max_length=100, choices=[("P", "President"), ("T", "Treasurer"), ("S", "Secretary"), ("EC", "EC members"), ("O", "Other members")]) member_email_id = models.EmailField(verbose_name = "Member's Email", max_length=100) member_from_date = models.DateField(verbose_name = "Member From", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now = True) member_to_date = models.DateField(verbose_name="Member To") deld_in_src_ind = models.CharField(max_length=20, choices=[("yes", "Yes"), ("no", "No")], blank=True, null=True) created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True, blank=True, null=True) created_by = models.ForeignKey(User, to_field='id', related_name = "assoc_created_by", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True, default=None) last_updated_date = models.DateField(verbose_name = "Updated Date", auto_now = True, blank=True, … -
ModuleNotFoundError: No module named 'django.forms.util'
I have a django model class which have a field of 'amount' I used pip install django-moneyfield install money field but I got an error when I run migration My Code: class Student(models.Model): user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) fee = MoneyField(decimal_places = 2, max_digits = 8, amount_default = Decimal("0"), currency_default = "INR", null = True, blank = True) Error -
how to send download link via mail in django
i want to send a download link via email using django.Any suggestions i already done some methods but didn't work body = 'Hello MR THIS MESSAGE FORM RECURITMENT APP The Persons You are looking for is Just Found.The Lists are given below : \n {0} {1} {2}'.format( ' '.join(str(name) for name in name_list), ' \n' , ' '.join(str(em) for em in email_list) ) + reverse('i.resume.path') message = EmailMessage("hello" , body,"********@gmail.com" , ['********@gmail.com'],['*******@gmail.com']) message.attach('data.csv', csvfile.getvalue(),'text/csv') message.send() the code for sending mail -
status update using Django
I am bigginer to learn Django and create a one Phototgrapher Website and I want add category status to user easily activate and deactivate category status how can I do this can any one help for this. I am not using Django admin panel I create Photographer Admin panel -
Deployment preview with ephemeral PostgreSQL
My architecture currently consists of a webapp built with Django and Webpack and deployed on Cloud Run. The build process consists of just a Dockerfile. When someone from my team opens a new PR, we would like for deployment to commence automatically to a new instance. This is explained here (deployment previews). However, I would like for an ephemeral database to also be spawn - similarly to what happens in Heroku. This is necessary because otherwise conflicting Django's migrations may damage Stage's database (e.g., both me and a teammate pushing two conflicting migrations).