Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Button not sending POST request to update object django
I have a scheduling app with Event objects and I'm trying to create a form that will allow the user to update an Event that already exists by the press of the button. However, when the user presses the button it doesn't seem to do anything. It just refreshes the page. {% for a in availability %} <form method='POST'> <li><a class="btn btn-primary" href="{% url 'updateevent' a.id %}" type="submit" role="button">{{a.day}}: {{a.start_time}} - {{a.end_time}}</a></li> </form> {% endfor %} view.py: def updateevent(request, pk): if request.method == 'POST': try: form = EventForm(data=request.POST, instance=post) updatedEvent = form.save(commit=False) updatedEvent.requester_user = request.user updatedEvent.notes = None updatedEvent.save() return redirect('/') except ValueError: print(form.errors) return render(request, 'events/createevent.html', {'form':EventForm(), 'error':'There was an error. Please make sure you entered everything correctly!'}) else: return redirect('/') I want the user that presses the button to become the "requester_user", a blank field in my Event object. How can I make this happen? -
Can I receive Django channels group messages in other part of my project
I am able to send to channels group from separate scripts using something like this from channels.layers import get_channel_layer async def somefunction(): await channel_layer.group_send( group_name, {"type": "system_message", "text": "demo text"}, ) What I want to know is, how can I also read updates from channel groups. Any help with be appreciated. -
Django Crispy forms helper throwing Failed lookup for key [helper] error
I cannot get crispy form helper to work with forms or formsets. If I simply user the {% crispy form %} or {% crispy formset %} tags, depending on implementation, the forms appear and function normally. Of course, this is a problem when I'm trying to use layouts with crispy helpers. When I user {% crispy form form.helper %} or {% crispy formset helper %}, my app throws errors that: Failed lookup for key [%s] in %r / Failed lookup for key [helper] error This is very strange as it only applies to helpers and I have tried passing in helpers, different attributes, and queryset data. I have tried using inlineformset_factory as well as modelformset_factory, and the outcomes are the same. I am trying to use inline formset factory with the parent as the logged in user. My user pk is a UUID (which gets another error related to these formsets: UUID object does not contain variable 'pk'). Here is my view: @login_required(login_url=reverse_lazy('login')) def real_property_req(request): # Import RealPropertyFormSet from forms.py current_user = CustomUser.objects.get(id=request.user.id) submitted = False if request.method == "POST": formset = RealPropertyFormSet(request.POST, instance=current_user) if formset.is_valid(): formset.save() return HttpResponseRedirect('?submitted=True') formset = RealPropertyFormSet(instance=current_user) context = {'formset': formset, 'submitted': submitted} return render(request, … -
Django {% for loop - showing 1 out of 3 values
I added for loop to my html, after I added more data to the Queryset. For some reason it's showing 1 out of 3 values I passed. - I could print them, it's just not showing up on the html. The result page - client_name (in blue), missing product_name + waiting_time (in red) Any ideas? thank you URLs.py ... path('orders/', views.orders_filter_view, name='orders'), ... Views.py def orders_filter_view(request): qs = models.Orders.objects.all() ... for order in qs: client = models.Clients.objects.get(pk=order.client_id) client_name = client.first_name qs.client_name = client_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<< product = models.Products.objects.get(pk=order.product_id) product_name = product.product_name qs.product_name = product_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< tz_info = order.created_date.tzinfo qs.waiting_time = order.created_date - datetime.datetime.now(tz_info) <<<<<<<<<<<<<<<<<<<<<<< total_matches = qs.count() context = { 'orders': qs, <<<<<<<<<<<<<<<<<<<<<<<<<<<<< 'view': 'הזמנות', 'total_matches': total_matches, 'titles': orders_titles } return render(request, 'adolim/orders.html', context) Orders.html {% for order in orders %} <tr> <td class="center">{{ order.client_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<< <td class="center">{{ order.product_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<< ... <td class="center">{{ order.delivery_person_name }}</td> {% if order.delivery_status == 'סופק' %} <td class="center green-text">{{ order.delivery_status }}</td> {% else %} <td class="center">{{ order.delivery_status }}</td> {% endif %} <td class="center yellow-text">{{ order.waiting_time }}</td> <<<<<<<<<<<<<<<<< The result page - client_name (in blue), missing product_name + waiting_time (in red) -
how to setup prometheus in django rest framework and docker
I want to monitoring my database using prometheus, django rest framework and docker, all is my local machine, the error is below: well the error is the url http://127.0.0.1:9000/metrics, the http://127.0.0.1:9000 is the begging the my API, and I don't know what's the problem, my configuration is below my requirements.txt django-prometheus my file docker: docker-compose-monitoring.yml version: '2' services: prometheus: image: prom/prometheus:v2.14.0 volumes: - ./prometheus/:/etc/prometheus/ command: - '--config.file=/etc/prometheus/prometheus.yml' ports: - 9090:9090 grafana: image: grafana/grafana:6.5.2 ports: - 3060:3060 my folder and file prometheus/prometheus.yml global: scrape_interval: 15s rule_files: scrape_configs: - job_name: prometheus static_configs: - targets: - 127.0.0.1:9090 - job_name: monitoring_api static_configs: - targets: - 127.0.0.1:9000 my file settings.py INSTALLED_APPS=[ ........... 'django_prometheus',] MIDDLEWARE:[ 'django_prometheus.middleware.PrometheusBeforeMiddleware', ...... 'django_prometheus.middleware.PrometheusAfterMiddleware'] my model.py from django_promethues.models import ExportMOdelOperationMixin class MyModel(ExportMOdelOperationMixin('mymodel'), models.Model): """all my fields in here""" my urls.py url('', include('django_prometheus.urls')), well the application is running well, when in the 127.0.0.1:9090/metrics, but just monitoring the same url, and I need monitoring different url, I think the problem is not the configuration except in the file prometheus.yml, because I don't know how to call my table or my api, please help me. bye. -
Heroku is rolling back my django app back to state when I deployed it. Every File and Data is being reset tot state when I deployed app
Heroku is rolling back. The staticfiles, mediafiles and database which i had deployed are always there but all those files and data added after deployment gets deleted after certain period. This is my Setttings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'rest_framework', 'news', 'Userprofile', 'search', 'bs4', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', 'news.context_processors.provider', 'news.context_processors.promotions', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have tried pushing with several changes but the heroku apps just resets again. PS all those database, static files, media files remains normal as I … -
jQuery DataTables is not a function error randomly occurring in Safari
I've been trying to use DataTables and other jQuery JS libraries in a Django-based web application. I call the .DataTable function in the document ready function. I have had no issues with Firefox and Chrome, but in Safari, some of the times I load the page, I get a .dataTable is not a function error, and the table does not render as a DataTables formatted table. However, other times I load the page, it seems to be working fine. Additionally, it seems that when there are issues with DataTables loading, other libraries also seem to have errors loading as well. I have ensured that jQuery is being imported only once, and prior to DataTables in the code. Even when the errors occur, it seems that DataTables is still being loaded by the browser. As I mentioned, the error only seems to happen in Safari and only seems to occur part of the time. Any insights? -
Set Model Field as Required in Django
Django doesn't enforce NOT NULL at the model/database level. device_serial is neither supposed to have blank '' nor null class Device(models.Model): device_serial = models.CharField(max_length=36, unique=True, null=False, blank=False) ....etc The statement below works totally fine! I expect it to fail because device_serial is required. It shouldn't accept empty string '' Device.objects.create(device_serial='') How can I make a field required at the model / database level? What could I possibly be doing wrong here? I don't see where did I go wrong. I tried ''.strp() to convert empty string to None but it didn't work -
Custom model permission in django-admin to edit a particular field
Normally, after migrating the models located in models.py, in django-admin you get a set of default permissions for your models. For example: models.py class Appointment(models.Model): time = models.TimeField(auto_now_add=False, auto_now=False, null=True, blank=True) notes = models.TextField(blank=True, null=True) In django-admin I can assign these permissions to a group: appname|appointment|Can add appointment appname|appointment|Can change appointment appname|appointment|Can delete appointment appname|appointment|Can view appointment However, I want to add a new permission to this list that will be able to allow a staff user to change the notes field only, such as: appname|appointment|Can change appointment notes I know I can add it like this: class Meta: permissions = [ ("change_notes", "Can change appointment notes"), ] However, the lines above will only add the permission to the list, and after assigning it to a group nothing happens (the notes field cannot be changed). How can I solve this? Is there any Django extension that can help me add a custom model permission in to edit a particular field? -
how to create a dynamic url in python (apiview,django)?
I want to dynamically add an id to an urlpattern and print that id to my server. for example on http://127.0.0.1:8000/experience/3 I want to print 3 to my server. from django.contrib import admin from django.urls import path,include from core.views import TestView from core.views import ExperienceView from core.views import ProjectView from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('experience/<str:id>', ExperienceView.as_view(),name='experience'), ] class ExperienceView(APIView): ... def delete(self,request,*args,**kwargs,id): connection = sqlite3.connect('/Users/lambda_school_loaner_182/Documents/job-search-be/jobsearchbe/db.sqlite3') cursor = connection.cursor() req = request.data print(id) return Response(data) -
Using DJANGO_SETTINGS_MODULE in a script in subfolder
In order to populate the database of my Django application, I created a small script that reads a CSV (a list of filenames) and creates objects accordingly: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') import django django.setup() import csv import sys from myapp.models import Campaign, Annotation campaign_name = "a_great_name" path_to_csv = "filenames.csv" with open(path_to_csv) as f: reader = csv.reader(f) filenames = [i[0] for i in reader] new_campaign = Campaign.objects.create(name=campaign_name) for i in filenames: new_annotation = Annotation( campaign=new_campaign, asset_loc = i) new_annotation.save() I saved this script at the root of my project: myrepo/populator.py and it worked fine. … until I decided to move it into a subfolder of my project (it’s a bit like an admin tool that should rarely be used): myrepo/useful_tools/import_filenames/populator.py Now, when I try to run it, I get this error: ModuleNotFoundError: No module named 'myproject' Sorry for the rookie question, but I’m having a hard time understanding why this happens exactly and as a consequence, how to fix it. Can anybody help me? -
Invalid urls structure in Django
I have a simple structure Shop_list --> Product_list --> Product_detail I hava an error. When I click to the shop I see products for ALL shops. The reason of the error is invalid urls.py logic I tried to use slug but did not receive result. I need to see products only for clicked shop I want to achieve it by this : start_url/ Click to the shop --> start_url/shop1_url Click to the product --> start_url/shop1_url/product1_url models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE) title = models.CharField(max_length=200) price = models.CharField(max_length=200) urls.py from .views import HomePageView, ProductListView, produt_detail urlpatterns = [ path('', HomePageView.as_view(), name='shop_list'), path('<int:pk>/', ProductListView.as_view(), name='product_list'), #path('tags/<slug>/', ProductListView.as_view(), name='product_list'), path('product/<int:pk>/', views.produt_detail, name='product_detail'), ] 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 produt_detail(request, pk): print(request) product = get_object_or_404(Product, pk=pk) return render(request, 'blog/product_detail.html', {'product': product}) shop_list.html {% for shop in shops %} <div class="col-md-4"> <div class="card mb-4 box-shadow"> <a href="{% url 'product_list' pk=shop.pk %}"> <img class="card-img-top" src="{{shop.image.url}}" alt="Card image cap" style="width:120px;height:120px;margin:auto;"> </a> ... {% endfor %} -
Creating choices in model based on other models
So what I want to do, is how can I create a choice (CUSTOMER_ADDRESS_CHOICE) to take customer_address field from Customers model or just typical string like "personal collection"? What i mean by that is for example: When my client want to collect his order from shop, it will outputs string but when he want to send it, it will shows up his address. class Customers(models.Model): textcustomer_id = models.AutoField(primary_key=True, null=False) customer_name = models.CharField(max_length=100, null=True) phone_number = models.CharField(max_length=9, null=True) customer_adrress = models.CharField(max_length=10, null=True) def __str__(self): return f'{self.customer_id}' class Meta: verbose_name_plural = "Customers" class Orders(models.Model): CUSTOMER_ADDRESS_CHOICE = ( ('ADRES KLIENTA', 'ADRES KLIENTA'), ('ODBIÓR OSOBISTY', 'ODBIÓR OSOBISTY'), ) STATUS_CHOICES = ( ('W TRAKCIE', 'W TRAKCIE'), ('ZAKOŃCZONE', 'ZAKOŃCZONE'), ) PAYMENT_STATUS_CHOICES = ( ('NIEZAPŁACONE', 'NIEZAPŁACONE'), ('ZAPŁACONE', 'ZAPŁACONE'), ) order_id = models.AutoField(primary_key=True, null=False) order_date = models.DateField(auto_now_add=True, null=True) customer_id = models.ForeignKey(Customers, on_delete=models.SET_NULL, null=True) customer_address = models.CharField(max_length=20, choices=CUSTOMER_ADDRESS_CHOICE, null=True) cost = MoneyField( decimal_places=2, default=0, default_currency='PLN', max_digits=11, ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, null=True) payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, null=True) def __str__(self): return f'{self.order_id}' class Meta: verbose_name_plural = "Orders" -
django.template.exceptions.TemplateDoesNotExist: index.html
Internal Server Error: / Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/amandeepsinghsaini/Django_projects/First_projects/first_app/views.py", line 6, in index return render (request,'index.html', context=my_dict) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html -
static files not found 404 django on development server
i couldn't find a solution after trying alot of solutions here, my problem is i'm running an ASGI app on a devlopement server and i can't get static files nor urls,it's working perfectly on local but not in server this server is running ubuntu and using apache2, i couldn't deploy because apache don't support asgi so i wanted just to run it as local , this is the apache conf on server ProxyPass /checkAuth2 http://localhost:8000 ProxyPassReverse /checkAuth2 http://localhost:8000 ProxyPreserveHost On so to run the app i should go to http://server/checkAuth2 settings.py BASE_DIR = os.path.abspath(os.path.dirname(file)) INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'checkurl', ] STATIC_URL = '/static/' print(BASE_DIR) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), index.html <link rel="stylesheet" href="{% static 'checkurl/css/bootstrap.min.css' %} "> <script src="{% static 'checkurl/js/jquery.min.js' %}"></script> <script src="{% static 'checkurl/js/bootstrap.min.js' %}"></script> path of static folder: project --checkurl --static --checkurl **--static** --css --js when i run server : i get this url http://server/checkAuth2/checkurl and for the files i get : http://server/checkurl/static/css.. which's not found i appreciate your help about this as i'm stuck here for 3 days, thank you! -
Creating view with fields depending on logged user permissions
I have my view class and I want to get access to specific fileds only for users with proper permissions. I tried way mentioned below but it take no effect. I suppose solution is very simple but I'm very new at Django and don't know all dependencies yet. class SimpleCreatelView(LoginRequiredMixin,CreateView): model = Simple template_name = 'mainapp/web.html' if User.is_superuser: fields = ['title','content','Comment'] else: fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
For Python's Django experts Chrome console in django doesn't work means console.log won't show any messages
Hello i'll try to go directly to the point with all the necessary details i have a django application working on a website with only html js css and some images. in javascript if i put console.log() anywhere in my javascript file it doesn't log any messages in the console alert() works pretty well javascript code works fine only my logs doesn't show up. note that i haven't done any changes in settings or any other parameters when this problem has came out i was only doing some javascript text and tried deleting it but nothing changes same problem persists knowing that if i try live server with or another server with the html js css... without django in the same path it logs everything and it works fine but in django it doesn't i've tried the cmd instead of shell it the same problem i the problem is in django's local server don't know how. Literally running a console.log() in the console itself returns undefined in the console, but not the console log itself as shown below. i'm using vs code, chrome, python 3.6 django last version i'm in this problem from yesterday i tried everything i wish to … -
No module named 'django_heroku'
I am trying to migrate my database to Heroku through: heroku run python3 manage.py migrate and I get this error: Traceback (most recent call last): `File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 222, in all return [self[alias] for alias in self] File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/learning_log/settings.py", line 134, in <module> … -
Preventing a hyperlink showing using CSS
A widget I use has this line of code as default. <a href="javascript:map_Location.clearFeatures()">Delete all Features</a> I don't want that hyperlink to be visible. I tried using - id_Location_span_map a:link { color: white; } But then I discovered there was other hyperlinks attached to the widget so I tried the following but none of them worked. #id_Location_span_map href="javascript:map_Location.clearFeatures()" { color: white; } /*#id_Location_span_map a:href="javascript:map_Location.clearFeatures()" { color: white; } #id_Location_span_map a:link href="javascript:map_Location.clearFeatures()" { color: white; } Does anyone have any other suggestions? Update Instead of {color:white} I will use {display:none}. But I still haven't figured out how to just apply the changes when the hyperlink is linking to a specific page. Update 2 This code solves my problem. Thank you to Gubasek Duzy and https://css-tricks.com/almanac/selectors/a/attribute/ for the help. a[href="javascript:map_Location.clearFeatures()"] { display: none; } -
How do I migrate data from the parent model/table to the child model/table?
So my child model inherits the parent model. After I run migrate, the child has a parent_ptr_id column referencing the parent. Great! But the child table remains empty while the parent table has data. How do I migrate the data from the parent table to the child table? I want to specify which columns to migrate from the parent table and which types of records to NOT migrate. This should be done automatically every time the parent table changes. Using Django v.3.0 -
Django trying to add an existing field when making a model managed
How can I stop Django 2.2.4 from trying to create a database column that already exists when making a model managed? I have 2 models, ticket and message, which were connected to tables in a third-party database so the models were created with managed=False. I'm moving away from the third-party tool. The ticket model was change to managed=True a while ago by somebody else, and now I'm trying to do the same with the message model. These are the relevant parts of the model: from django.db import models class Message(models.Model): mid = models.BigAutoField(db_column='MID', primary_key=True) ticket = models.ForeignKey('Ticket', on_delete=models.CASCADE, db_column='TID') author = models.CharField(db_column='AUTHOR', max_length=32) date = models.DateTimeField(db_column='DATE') internal = models.CharField(db_column='INTERNAL', max_length=1) isoper = models.CharField(db_column='ISOPER', max_length=1) headers = models.TextField(db_column='HEADERS') msg = models.TextField(db_column='MSG') class Meta: # managed = False db_table = 'messages' permissions = ( ("can_change_own_worked_time", "Can change own worked time"), ("can_change_own_recently_worked_time", "Can change own recently worked time"), ("can_change_subordinate_worked_time", "Can change subordinate worked time"), ) This are the migrations that get generated by commenting out managed=False: # Generated by Django 2.2.4 on 2020-06-18 20:56 (0017_auto_20200618_1656) from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('troubleticket', '0016_auto_20200511_1644'), ] operations = [ migrations.AlterModelOptions( name='message', options={'permissions': (('can_change_own_worked_time', 'Can change own worked time'), ('can_change_own_recently_worked_time', 'Can change own … -
alternatives to gmail usage for django password reset
settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_USE_TLS = True EMAIL_HOST_USER = "myemail" EMAIL_HOST_PASSWORD = "mypassword" i am trying to implement django password reset, but i need to create app password in gmail which requires two-step verification which is not allowed by google in my country Nigeria what alternative do i have so i can implement django password reset? -
How to edit a BoleanField in Django
please i need your help been stuck like this for days,here is my problem, i have a profile page of a user that contain a BooleanField and a Button if the user would like to subscribe or not, i am wanting to design it this way, in which their will only be a one click button that will show Subscribe and once clicked you you get redirected to the payment page then you choose your plan and make payment,then in the user info it will show a dead btn of Subscribed and underneath would be the code generated for a specific task,just help me share even if its a link to a tutorial to follow as a starting point,here is my code and the picture model.py 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) html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h4 text-center center">Your Email</legend> <legend class=" mb-4 h3 center text-center">{{ user.email }}</legend> </fieldset> <div class="form-group text-center center"> <button class="btn btn-outline-info" type="submit">{{ user.patient.subscribe }} </button> </div> </form> -
Django + DRF and Domain Driven Design
Recently, I meet such concept as Domain Driven Design and opinion, that usual DRF application (CRUD enpoints) are not satisfied DDD consepts. Does really django-rest-framework uses different patterns and can't be implemented with DDD? Some example (if I understand everything right) There is a table called Items. There are two cases - 1) api should return all items with is_published=true 2) api should return all items DRF - one endpoint with filtering 1) /items/?is_published=1 2) /items/ DDD - two endpoints, because there is two different domain objects 1) /published_items/ 2) /all_items/ -
Sum of model methods django
I'm trying to get the sum of some of my model methods and display them on a results page. I'm not sure how possible it is to get this done in my views.py. I get the following error when I run the server. Unsupported operand type(s) for + 'method' and 'method' models.py class Organization(ModelFieldRequiredMixin, models.Model): exist = models.BooleanField(help_text='Does organization exist physically?') blacklist = models.BooleanField(help_text='Has organization previously been blacklisted by a national authority, funder or fund manager?') grant_amount = MoneyField(decimal_places=2, max_digits=12, help_text='Total amount of grant(s) from largest donor to organization ') estimatedAnnual_budget = models.IntegerField(help_text='Estimated annual budget of the organization (inclusive of the largest funder), in US Dollars') class Scores(ModelFieldRequiredMixin, models.Model): organization = models.ForeignKey(Organization,on_delete=models.CASCADE) score = models.DecimalField(max_digits=9, decimal_places=2) # Section1 - ORGANIZATIONAL BACKGROUND def exist_score(self): if self.organization.exist == True: self.score=0.1 return self.score #The higher score else: score=0.1 return self.score #The lower score def accessibility_score(self): if self.organization.accessibility == True: self.score=5 return self.score else: score=0 return self.score def blacklist_score(self): if self.organization.blacklist == True: self.score=0 return self.score else: score=0 return self.score # Section2 - PREVIOUS GRANTS & PERFORMANCE def grant_amount_score(self): if self.organization.grant_amount >= 2000000: self.score=3.5 return self.score else: score=0 return self.score def estimatedAnnual_budget_score(self): if self.organization.estimatedAnnual_budget == True: self.score=2 return self.score else: score=0.1 return self.score Views.py …