Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Time and date calculations DJango
So i have a data entry project using django and i have those 4 fields representing the: start_date, start_time, end_date, and end_time {% block content %} <h1>Form Page</h1> {% csrf_token %} {{ form.start_date.label_tag }} {{ form.start_date }} {{ form.start_time.label_tag }} {{ form.start_time }} {{ form.end_date.label_tag }} {{ form.end_date }} {{ form.end_time.label_tag }} {{ form.end_time }} {{ form.duration_hours.label_tag }} {{ form.duration_hours }} Submit {% endblock %} so the thing that i need is to make a listener for those 4 field values and whenever the user entered the first 3 values and start filling up the forth one which will be the end time the duration_hours field will start to calculate the difference between and give me the value of the duration time. All models,forms python files are correct i just want to know how i can do it I tried to make a script in the html file like this : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"\>\</script\> $(document).ready(function(){ // get the values of the start and end date/time fields var start_date = $("#start_date input").val(); var start_time = $("#start_time input").val(); var end_date = $("#end_date input").val(); var end_time = $("#end_time input").val(); // combine the start date/time and end date/time into Date objects var start_datetime = new … -
Count objects in queryset by value in a field
I have a queryset that is returned by the server: queryset = Item.objects.all() ItemSerializer(queryset, many=True).data [OrderedDict([('id', '123'), ('status', 'Available')]), ... OrderedDict([('id', '321'), ('status', 'Confirmed')])] I can get the number of items by status: queryset.values('status').annotate(Count('status')) <QuerySet [{'status': 'Available', 'status__count': 3}, {'status': 'Confirmed', 'status__count': 2}]> As a result, I am trying to get such a response from the server: [{"id":"123","status":"Available"}, ... {"id":"321","status":"Confirmed"}, {"status": "Available", "status__count": 3}, {"status": "Confirmed", "status__count": 2}] -
Tools to help in analyzing and reviewing large python code base
I have a large Django code base which I want to analyze and review.Is there any tools that can help me to do this efficiently like explain the code architecture,flow and give me high level overview? -
Django Smart Selects not working for django admin
So I'm trying to implement django-smart-selects 1.5.9 for django 1.11.4 and somehow the chained keys dont work the way they should. models.py class Province(models.Model): name = models.CharField( max_length=30 ) class Meta: verbose_name = _("province") verbose_name_plural = _("provinces") def __str__(self): return self.name class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("district") verbose_name_plural = _("districts") def __str__(self): return self.name class City(models.Model): district = models.ForeignKey( District, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("city") verbose_name_plural = _("cities") def __str__(self): return self.name class Ward(models.Model): city = models.ForeignKey( City, on_delete=models.CASCADE ) name = models.CharField( max_length=2 ) class Meta: verbose_name = _("ward") verbose_name_plural = _("wards") def __str__(self): return self.name class School(models.Model): # other fields ..... province = models.ForeignKey( Province, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("province") ) district = ChainedForeignKey( District, chained_field="province", chained_model_field="province", show_all=False, ) city = ChainedForeignKey( City, chained_field="district", chained_model_field="district", show_all=False, ) ward = ChainedForeignKey( Ward, chained_field="city", chained_model_field="city", show_all=False, ) urls.py url(r'^admin/', admin.site.urls), url(r'^admin/', include('smart_selects.urls')), admin.py @admin.register(School) class SchoolAdmin(admin.ModelAdmin): inlines = [ServerInline, ServerUpdateInline] list_display = ['school_name', 'school_type','phone', 'province', 'district', 'city', 'ward', ] search_fields = ('school_name','district__name') list_filter = ('school_type', 'district') here tried the chained dropdown implementation from django-smart-selects the models and admin … -
Relate model to itself in django for recommendations
Im trying to relate django model to itself. I have Product table and recommendations column. I wanna relate recommendations to itself. How can I do it? class Product(models.Model): @property def image_url(self): if self.img and hasattr(self.img, 'url'): return self.img.url name_tm = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) child_category = models.ForeignKey(Child_Category, on_delete=models.CASCADE, related_name='child_category') show = models.BooleanField(default=True) description_tm = models.TextField(blank=True, null=True) description_ru = models.TextField(blank=True, null=True) description_en = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=8) ready_time = models.PositiveIntegerField(null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) recommendations = models.ManyToManyField(Product, blank=True, null=True) img = models.FileField(upload_to=upload_to, null=True) def __str__(self): return self.name_en -
Fail to load resource: the server responded with a status of 404. in the STATICFILES_DIRS setting does not exist
I'm trying to put image on my website with Django. But it always give an error 404, Tried many things, but it still be the problem. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] STATIC_URL = '/static/' {% load static %} <!DOCTYPE html> <html> <img src="{% static 'media/logo2.jpeg' %}" alt="photo" height="100" width="500"> <p>HEllo world</p> {% block content %} replace me {% endblock %} </html> Wanna to have image on the website! -
Celery crashing error: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?)
I am using celery in my django project to run some tasks in async. But the celery on server is crashing repeatedly. Error message: Mar 20 10:47:51 QA celery[663]: chan.handlers[type]() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/kombu/transport/redis.py", line 896, in _brpop_read Mar 20 10:47:51 QA celery[663]: dest__item = self.client.parse_response(self.client.connection, Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/client.py", line 1192, in parse_response Mar 20 10:47:51 QA celery[663]: response = connection.read_response() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/connection.py", line 829, in read_response Mar 20 10:47:51 QA celery[663]: raise response Mar 20 10:47:51 QA celery[663]: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?) Mar 20 10:47:51 QA systemd[1]: celery.service: Deactivated successfully. Mar 20 10:47:51 QA systemd[1]: celery.service: Consumed 2.439s CPU time. Can anyone help? Is there any was to prevent this error. -
Pytest-django does not seem to create a new database for each test
When I run a test that needs the database, it seems to use the existing database (when I change a database entry, the test error contains the changed database entry). But I expect that pytest-django creates a new database for each test (if not specified differently). When debugging it calls the custom django_db_setup and the pytest django_db_setup fixture. It also outputs in the log statement: "Running migrations: Applying ..." but the test fails when I manipulate the data in the existing database. Could it be that the problem is there because we use an in memory Sqlite database? Or do I need some other setting? Or is this a bug? Test: def test_should_show_the_city_name_in_city_select_dropdown(page: Page, django_db_setup): page.goto("/") city_select_button = page.get_by_text("Stadt auswählen") city_select_button.click() assert "Beispielstadt" in page.get_by_role("listitem").all_inner_texts() conftest.py import os import pytest from django.core.management import call_command from config.settings.base import BASE_DIR os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" @pytest.fixture(scope="session") def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command( "loaddata", os.path.join(BASE_DIR, "e2e_tests", "database", "test_database.json"), ) pyproject.toml [tool.poetry.dependencies] python = "^3.10" django = "^4.1.6" [tool.poetry.group.dev.dependencies] pytest = "^7.2.1" pytest-playwright = "^0.3.0" pytest-base-url = "^2.0.0" pytest-django = "^4.5.2" [tool.pytest.ini_options] base_url = "http://localhost" DJANGO_SETTINGS_MODULE = "config.settings.local-container" database settings DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": Path("/") / "db" / "db.sqlite3", } } -
Django UpdateView not working showing slug error
I'm having issues with my creating an update view to update aspects of a model. Below is the code urls from django.urls import path, include from . import views urlpatterns = [ path('', views.Tenant_selector.as_view(), name='Tenant_selector'), path('<slug:slug>/dashboard', views.Dashboard.as_view(), name='Dashboard'), path('<slug:slug>/updateTenant', views.EditTenant_View.as_view(), name='UpdateTenant'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), path('<slug:slug>/sync', views.sync_view.as_view(), name='Sync'), path('success', views.Success.as_view()), path('<slug:slug>/loading', views.sync_loading.as_view(), name='Loading'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), ] views from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, UpdateView from django.views.generic import TemplateView, DetailView, ListView from account.forms import CreateTenant, EditTenant from account.models import Tenant, staff_sync_model, student_sync_model from main.forms import RegisterForm, EditUser from main.models import NewUser from django.http import HttpResponse from datetime import date from . import Sync class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.data = Tenant.objects.get(slug=self.request.path.split("/")[2]) context['total'] = self.data.staff.count() + self.data.student.count() context['staff'] = self.data.staff.count() context['student'] = self.data.student.count() context['slug'] = self.request.path.split("/")[2] return context class CreateTenant_View(CreateView): model = Tenant form_class = CreateTenant template_name='CreateTenant.html' success_url='/account/success' def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return redirect('/account/success') class EditTenant_View(UpdateView): model = Tenant form_class = EditTenant template_name='UpdateTenant.html' success_url='/account/success' def form_valid(self, form): form.save return redirect('/account/success') class Success(TemplateView): template_name='success.html' class Tenant_selector(ListView): model = Tenant template_name = 'Tenant_selector.html' def get(self, request, *args, **kwargs): if self.request.user.is_authenticated: data = self.request.user.tenant_set.all() if len(data) … -
Cannot parse data into {% include %} tag - Django
i have forum.html template inside templates/forum directory <div style="height:50px; width:100%">welcome to forum {{ obj.forum_name }}</div> i want to include this template into my topic.html template which is inside same directory. and i want to pass data using with {% include 'forum/forum.html' with obj.forum_name="windmaker" %} However it does not work as expected. It gives me "with" in 'include' tag needs at least one keyword argument. error. What can i do? As far as i understood the problem arise from dot(.) operator. I tried not to using it and suddenly it renders the page correctly here i get rid of .forum_name inside forum.html <div style="height:50px; width:100%">welco to forum {{ obj }}</div> and here i passed data inside topic.html {% include 'forum/forum.html' with obj="windmaker" %} and suddenly it works! -
from django.contrib.auth.models import User error in class Meta:
I'm having a problem to create a User inside class Meta I saw some things related to the same problem but could not solve with the solutions they gave. Here the problem: enter image description here I had this same problem in models.py but looking a little on the internet I could find how to fix and had to import the settings and create the user with this AUTH_USER_MODEL enter image description here I tried to do the same thing on the form but I got these two errors. enter image description here enter image description here And when trying to put only the settings.AUTH_USER_MODEL I can not put the server to run because it gives me this error in the Meta class and when I replace for example an empty string it runs normally but then I will not be creating the user. enter image description here enter image description here -
How do i limit choices for a field in a django model with respect to the data in previous field using foreignkey and limit_choices_to attribute?
class Property(models.Model): property_name = models.CharField(max_length=100) unit_name = models.CharField(max_length=100) class Tenant(models.Model): tenant_name = models.CharField(max_length=100) rent_unit = models.ForeignKey(Property, on_delete=models.SET_NULL) class Payment(models.Model): payment_name = models.ForeignKey(Tenant, on_delete=models.SET_NULL) payment_property = models.ForeignKey(Property, on_delete=models.SET_NULL, limit_choices_to={ 'pk__in': Property.objects.filter(unit_name=models.OuterRef('payment_name__rent_unit__unit_name')) }) I'am trying to limit the choices for the payment_property field in the Payment model based on the selected rent_unit in the Tenant model using Django's ForeignKey.limit_choices_to attribute with a subquery. But am getting this error when trying to execute makemigrations. ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. i was expecting to get a single choice for payment_property whenever i create a new Payment object and select a Tenant object, the available choices for the payment_property field should be limited to Property objects that have the same unit_name as the rent_unit of the selected Tenant object. -
I have got error when ı add trying to add column in my sqlite database in django
ı have trying to change my database to postgreSQL but but whenever ı have trying to makemigrations ı got an Error which attached on bellow: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such column: Projects_project.abbr The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 21, in <module> main() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 395, in execute django.setup() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin_init_.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\cukad\AppData\Local\Programs\Python\Python311\Lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\Projects\admin.py", line 24, in <module> class ProjectListFilter(admin.SimpleListFilter): … -
Django User Model Optimization
UserModel has many entries on it. The 3 UserModel queries run very slow. How to make needed changes and optimizations to UserModel to make the 3 queries run faster? class UserModel(models.Model): username = CharField(max_length=255) role = JSONField() # format of ['admin', 'operator'] UserModel.objects.filter(username='john').first() UserModel.objects.filter(username__contains='doe').first() UserModel.objects.filter(role__contains='operator').first() -
Django manual reset password handling
Our system based without physical templates. All templates stored in database. Template render with HttpResponse and Template classes. I cant use django built-in GenereicViews. How can i manualy handle forgot password and reset password logic, email sending with a unique link? -
get user group name from a specific text in django
In django, user posts in a simple HTML form. In form, there is a field which called "technician_name". I'm getting the post with "name attribute" and write it to database. I want additional thing: after I take the name attribute, I want to check the group of technician. Simply: I want to check user's group according to specific text. For example: user posted the "John Doe". if request.method == 'POST' action_man = request.POST.get('technician_name') Output: action_man = "John Doe" I need this action_man's user group. The action_man's name same with username, so I can query in django auth. Note: I don't need the logged in user's group. I need action man's group. -
Avoid CSRF_TRUSTED_ORIGINS in Django 4.1
I've a dockerized Django project which I access through NGINX. I just upgraded to Django 4.1 and now it seems that it's mandatory to define a CSRF_TRUSTED_ORIGINS listing, I would like to know if there is a way to allow POST requests from any source. I've tried installing https://github.com/ottoyiu/django-cors-headers and setting CORS_ALLOW_ALL_ORIGINS to TRUE but it didn't work :/ Also I tried setting CSRF_TRUSTED_ORIGINS = ['*'] as I have in ALLOWED_HOSTS but it doesn't work... Thank you so much! -
How to use load static (django) in css file for background webkit
How to use {% load static%} in css file for background webkit ? What should i do to get this ? I've tried using {%load static%} in css file but that doesn't work. -
TypeError: 'WSGIRequest' object is not callable
Intento mostrar el modelo de detección de señas en las vistas de django. Pero tengo ese mensaje de error y no me carga la cámara. Estos son mis códigos from django.shortcuts import render from django.http.response import StreamingHttpResponse from PROTOTIPO.step_5_camera import main, center_crop # Create your views here. def home(request): return render(request,'home.html',{}) def sistema(request): return render(request,'Sistema.html',{}) def gen(center_crop): while True: frame=center_crop.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(main): return StreamingHttpResponse(gen(main()), content_type='multipart/x-mixed-replace; boundary=frame') import cv2 import numpy as np import onnxruntime as ort def center_crop(frame): h, w, _ = frame.shape start = abs(h - w) // 2 if h > w: return frame[start: start + w] return frame[:, start: start + h] def main(): # constantes index_to_letter = list('ABCDEFGHIKLMNOPQRSTUVWXY') mean = 0.485 * 255. std = 0.229 * 255. # se crea una sesión ejecutable con el modelo exportado ort_session = ort.InferenceSession("signlanguage.onnx") cap = cv2.VideoCapture(0) while True: # Captura de cuadro por cuadro ret, frame = cap.read() # preprocesamiento de los datos frame = center_crop(frame) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) x = cv2.resize(frame, (28, 28)) x = (x - mean) / std x = x.reshape(1, 1, 28, 28).astype(np.float32) y = ort_session.run(None, {'input': x})[0] index = np.argmax(y, axis=1) letter = index_to_letter[int(index)] cv2.putText(frame, … -
how to deploy django with nginx,guniorn and postgresql
Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine -
Level of logger in django project app view is undefined
When i initialize the logger in the views.py of my app in my django project, the loglevel is undefined althoug i defined it as INFO in the settings.py. I pass the loglevel as a environment variable (I also checked that it is correctly set to INFO by debugging it). When I check the level of the logger in the views.py it always is 0 which means undefined. I also tried to add a root block to the settings and change the name variable to "django" to load the logger both didn't worked. Maybe anyone can tell me what I am missing? Logging config in settings.py: LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py: logger = logging.getLogger(__name__) def teams_overview(request): try: logger.error("error") logger.warning("warning") logger.critical("critical") logger.info("info") logger.debug("debug") output: loglevel of logger: 0 error warning critical Project Strucutre: … -
Django ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
I have a usecase model, I'm trying to update the fields in the model. I have delivery date and estimated delivery date. It seems that delivery date is not able to update alone. If I update estimated delivery along with delivery date it gets updated. otherwise it shows an error: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] my model: class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) usecase_description = models.CharField(max_length=5000) delivery_date = models.DateField() my views: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0], "usecase_types": UsecaseType.objects.all(), "usecase_kpis": Kpi.objects.all()} if request.method == "POST": usecase_type = request.POST['usecase_type'] kpi = request.POST['kpi'] estimated_date = request.POST['estimated_date'] delivery_date = request.POST['delivery_date'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_type_id=usecase_type usecase_details.kpi_id=kpi usecase_details.estimated_date=estimated_date usecase_details.delivery_date=delivery_date usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except Exception as e: print(e) messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="project-name">Usecase Type:</label> <select name="usecase_type" class="custom-select my-1 mr-sm-2" id="usecase_type"> {% for usecase_type in usecase_types %} … -
it is possible to preview template html file before saving it using the Django admin app?
it is possible to preview template Html file before saving it using the Django admin app?? I am try to make overriding template preview button on admin panel but i can't make this I am try to image preview button -
I want to use "if and elif" Inside the Send_mail function in Django
What I want to achieve is I want to use "if and elif" Inside the Send_mail function in Django but an error occurs and I don't know how to fix it... Error message potential arugment cannot appear after keyword aurgument send_mail( subject='New message', message='Access to http://localhost:3000/messagerooms', from_email=settings.EMAIL_HOST_USER, if inquiry_user == self.request.user: recipient_list = post.user.email elif post.user == self.request.user: recipient_list = inquiry_user.email ) -
I am trying to read TID of RFID tag from Chafon CF-RU 5102 in python, i am getting EPC rather than TID
i am following this link, https://github.com/wabson/chafon-rfid, and getting EPC not TID which is a universally unique Tag ID. i am getting 000000000000000000000000 as EPC, whereas E280F336200060000065DDBE is some what expected to be read