Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ListView how to make query I need in class as I had it before in my function
I'm new at django and did my first project using book Eric Matthews python crash course, but now I'm trying do it better and change function that works perfectly into class, but can not get how to make it in Class the same query by filtering public and not public "topics" for users. Could somebody give me advice please how it works in classes? The function which is works perfectly and then the class I need worked like this function: def topics(request): """Provide list of topics.""" public_topics = Topic.objects.filter(public=True).order_by('date_added') if request.user.is_authenticated: private_topics = Topic.objects.filter(owner=request.user).order_by('date_added') topics = public_topics | private_topics else: topics = public_topics context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) And there is the class I need that it worked like the previous function. Could you advice what should be in queryset with public, owner and request? class TopicsHome(ListView): model = Topic template_name = 'learning_logs/topics.html' context_object_name = 'topics' def get_queryset(self): return Topic.objects.filter(public=True).order_by('date_added') -
Why do localize template tag and USE_L10N sometimes produce different results?
According to Django docs, the localize template tag allows for more fine-grained control of localization in templates than the general USE_L10N = True setting. However, turning localize on doesn't always produce the same result as setting USE_L10N = True. For example, # USE_L10N = True in settings.py {% load l10n %} {{some_datetime_value|date}} # Date is shown and localized vs # USE_L10N = False in settings.py {% load l10n %} {% localize on %} {{some_datetime_value|date}} {% endlocalize %} # Date is shown and NOT localized Why are the two results different? And is there a way to make the localize tag localize correctly in those cases? -
Django serialization get foreign key table value istead of id
recently i started on django framework and i am stuck at this situation tried reading documentation but my lack of experience i am not able understand much is there any way we can get response how we wanted with keeping django default checks,validation as much as possible. i tried using def to_representation but still it's giving me reponse as null when i debug. use case: i have mention model below i want foreign key value as text what stored in table status_lookup.name from product table class product_serializer(serializers.ModelSerializer): status = status_lookup_serializer(read_only=True,many=False) class Meta: model = product fields = ('id','name','status_id','status') model.py class status_lookup(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True) activation_date = models.DateTimeField(auto_now_add=True) deactivation_date = models.DateTimeField(blank=True,default=None) def __str__(self): return self.name class product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) img_url = models.CharField(max_length=255,blank=True) status_id = models.ForeignKey(status_lookup, related_name='status', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True) activation_date = models.DateTimeField(auto_now_add=True) deactivation_date = models.DateTimeField(blank=True,default=None) def __str__(self): return self.name o/p I want [ { "id":1, "name":"xxx", "status":pending } ] -
How to correctly use Django defer() when CONCAT to large textfield
I have a textfield with lots of data (>400000 lines of text). I think this is the reason that my server sometimes suddenly denies service when many users append new text lines. I am using so far Item.objects.filter(pk=iitem.pk).update(html=Concat("html", Value(msg))) to append a new msg. But I think the problem is that beforehand I have to check some other fields of iitem, so I do iitem = IMPALitem.objects.get(pk=p["iibox"]). Am I correctly assuming, that this is where all the data (40MB) gets unnecessarily loaded from the DB (postgres) into memory!? Is changing the get to iitem = IMPALitem.objects.get(pk=p["iibox"]).defer("html") all I need to do? (Does the defer() need to go left/in-front-of the get()?)? -
Django REST generic ListCreateView GET request is working but POST request is not working
I created a generic ListCreateAPI view. I am able to execute a GET request to the view but not a POST request. Here is my model: class InvoiceEntry(models.Model): SERVICE_OR_EXPENSE_CHOICE = [('SER', 'Service'),('EXP', 'Expense')] TYPE_CHOICE = [('BPA', 'BPA'),('CAE', 'CAE'),('MEC', 'MEC'),('TRA', 'Travel')] invoice_number = models.CharField(max_length=20) description = models.CharField(max_length=200) rate = models.FloatField() units = models.FloatField() discount = models.FloatField(default=0) amount = models.FloatField() service_or_expense = models.CharField(max_length=10, choices=SERVICE_OR_EXPENSE_CHOICE) type = models.CharField(max_length=10, choices=TYPE_CHOICE) def __str__(self): return '[' + str(self.invoice_number) + '][' + self.description + '][' + self.service_or_expense + '][' + self.type + ']' Here is my view: class InvoiceEntryListCreate(ListCreateAPIView): queryset = InvoiceEntry.objects.all() serializer_class = InvoiceEntrySerializer And here is my serializer: class InvoiceEntrySerializer(serializers.ModelSerializer): class Meta: model = InvoiceEntry fields = ['invoice_number', 'description', 'rate', 'units', 'discount', 'amount', 'service_or_expense', 'type'] I get the following error when trying a post request: { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } -
Cannot import name 'BlobClient' from 'azure.storage.blob. Django
Although, there are many similar questions to the one I am asking, but non of them have helped me. I am trying to store the file into my azure storage blob through directly through my system using Django. can some help me? Here is the result of pip freeze: azure-nspkg==3.0.2 azure-servicebus==0.21.1 azure-servicefabric==6.3.0.0 azure-servicemanagement-legacy==0.20.7 azure-storage-blob==1.5.0 azure-storage-common==1.4.2 azure-storage-file==1.4.0 azure-storage-queue==1.4.0 I got the following importerror: from azure.storage.blob import ( ImportError: cannot import name 'BlobClient' from 'azure.storage.blob' -
How to prevent Django TestCase creating SQL table with prefixes?
I have started building TestCase for API which used Django Rest Framework. But the moment I started, I realized the database TestCase created included prefixes in my table. I know I can change the table name to be more Django-friently but I don't think it will work with my current MySQL setup. This is the error I got. django.db.utils.ProgrammingError: (1146, "Table 'test_db.foo' doesn't exist") And when I run with --keepdb, the table it created is api_foo, where api is where the models.py is stored Is there a way to prevent Django from renaming my table name at all? -
Django reverse foreign key constraint
I have 2 models, Asset and Trade. The Trade model has Asset linked by a foreign key, which allows null values depending on the status of the Trade. An Asset always needs to be linked to a Trade by the foreign key. An Asset can have many Trades, but a Trade can only have 1 Asset. The problem is that sometimes an Asset is created without a Trade, and this needs to fail because it then causes further errors as it shouldn't be possible. How can I ensure the reverse foreign key is never null for the Asset model, but keep the on_delete parameter as SET_NULL? class Trade(models.Model): status = models.CharField(max_length=10) asset = models.ForeignKey( Asset, on_delete=models.SET_NULL, blank=True, null=True, ) class Asset(models.Model): price = models.DecimalField(max_digits=16, decimal_places=2) -
Got No such file or directory while using uWSGI
Ubuntu 20.04 Desktop, uWSGI 2.0.18-debian, Django 3.2.9, NGINX 1.18.0-0ubuntu1.2, Python 3.8.10; here is my uWSGI configuration file /etc/uwsgi/apps-enabled/mysite.ini [uwsgi] http-socket = 127.0.0.1:8081 stats = 127.0.0.1:8082 stats-http=true uid = www gid = www chmod-socket = 666 chown-socket = www chdir = /home/www/mysite home = /home/www/.python3.8_mysite pidfile = /run/uwsgi/app/mysite/pid socket = /run/uwsgi/app/mysite/socket py-tracebacker = /tmp/tbsocketmysite touch-chain-reload = /home/www/mysite/reload module = mysite.wsgi plugin = python3 master = true vacuum = false memory-report = true lazy-apps=true listen = 65535 buffer-size = 32768 workers = 1 enable-threads = true threads = 1 When i try to restart the uWSGI service: service uWSGI restart It goes wrong: Job for uwsgi.service failed because the control process exited with error code. See "systemctl status uwsgi.service" and "journalctl -xe" for details. So i go to check the uWSGI log file /var/log/uwsgi/app/mysite.log Fri Nov 26 16:17:20 2021 - *** Starting uWSGI 2.0.18-debian (64bit) on [Fri Nov 26 16:17:20 2021] *** Fri Nov 26 16:17:20 2021 - compiled with version: 10.0.1 20200405 (experimental) [master revision 0be9efad938:fcb98e4978a:705510a708d3642c9c962beb663c476167e4e8a4] on 11 April 2020 11:15:55 Fri Nov 26 16:17:20 2021 - os: Linux-5.11.0-40-generic #44~20.04.2-Ubuntu SMP Tue Oct 26 18:07:44 UTC 2021 Fri Nov 26 16:17:20 2021 - nodename: ubuntu-desktop Fri Nov 26 16:17:20 2021 - … -
How can I automatically generate a url for a specific item in Angular
For example i have different items from the database and would like to share a link that will let someone to specific item only without showing other related items, eg i have football, volleyball among others, so you are playing football, you should get a link to take you to football page to register there. -
I am trying to add many to many feild in django but getting error
models are- class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) seller=models.ForeignKey(Seller,null=True,on_delete=models.CASCADE,) category = models.ForeignKey(Category,null=True, on_delete=models.CASCADE,) description = models.CharField(max_length=200, default='' , null=True , blank=True) image = models.ImageField(upload_to='uploads/products/') rating=models.FloatField(null=True) people=models.IntegerField(default=0,null=True) customers=models.ManyToManyField(Customer,blank=True) class Customer(models.Model): user_name = models.CharField(max_length=50) phone = models.IntegerField(default='8928') email = models.EmailField() password = models.CharField(max_length=500) qq=Product.objects.get(id=8) print(qq) print(Customer.objects.all().first()) qq.customers.add(Customer.objects.all().first()) print("qq.customers is",qq.customers) """ Product object (8) Customer object (1) qq.customers is store.Customer.None""" I want to know how we can add customers in product.customers which is showing none in this problem .Please help me to solve this -
Update field on another table when add new record - django
I have a form where adding appointments. I would like to update a field in another table during submission. Let me illustrate: accounts model (Custom user model) class Account(AbstractBaseUser): patient_status = ( ('No Patient', _('No Patient')), ('New Patient', _('New Patient')), ('Patient', _('Patient')), ) first_name = models.CharField(_('First Name'), max_length=50) last_name = models.CharField(_('Last Name'), max_length=50) username = models.CharField(_('Username'), max_length=50, unique=True) ... # required is_patient = models.CharField(_('Patient'), max_length=20, choices=patient_status) ... views.py adding appointment: def add_appointment(request): form = AddAppointmentForm(request.POST or None) if request.method == 'POST': if form.is_valid(): appoint_user = form.cleaned_data.get('user') appoint_seat = form.cleaned_data.get('seat') appoint_start_appointment = form.cleaned_data.get('start_appointment') appoint_end_appointment = form.cleaned_data.get('end_appointment') # If Appointment already exist if Appointment.objects.filter(user=appoint_user, seat=appoint_seat, start_appointment=appoint_start_appointment, end_appointment=appoint_end_appointment).exists(): messages.warning(request, "This appointment already exists.") else: form.save() messages.success(request, 'Appointment was added successfully!') return redirect('appointments:add_appointment') else: form = AddAppointmentForm() I would like to update is_patient after is_valid(), something like: patient = Appointment.objects.filter(user=appoint_user).count() if patient > 0: patient.user__is_patient = 'Patient' patient.save() How can i access is_patient from Account's table in order to update and also where is the right place to put the code, in the view? -
How to save a nested object in separate models in Django?
I'm trying to save a nested object into two different tables in my Django app. I'm missing something because I get validation errors from the sub Model. The data in my events is not recognized and the serializer validation fails. Do I need to modify my serializer somehow or is there something wrong with my Models? I have these two Models: class Plan(models.Model): name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) Then I have these serializers for my Models: class PlanEventSerializer(serializers.ModelSerializer): class Meta: model = PlanEvent fields = '__all__' class PlanSerializer(serializers.ModelSerializer): events = PlanEventSerializer(many=True) class Meta: model = Plan fields = ('name', 'events') def create(self, validated_data): events_validated_data = validated_data.pop('events') plan = Plan.objects.create(**validated_data) plan_event_serializer = self.fields['events'] for p in events_validated_data: p['plan'] = plan events = plan_event_serializer.create(events_validated_data) return plan In my views.py I do this: class PlanView(APIView): permission_classes = [AllowAny,] serializer_class = PlanSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I try to save a Plan and the PlanEvent into their own table with this payload: { "name": "some name", "events": [ { "done": false, "title": "some title" }, { "done": true, "title": "some title" … -
Correct way to use URL Patterns, Views & Templates when using the Django Abstract base classes for my models
Are there better approaches to this problem? This model structure is what I am after for my database. So I am feeling like I am breaking the DRY rule with my learning project. Using Django 3.2.9 & Python 3.9.6 I have looked around the internet on how to get this more dynamic in the views, urls & templates but I have not had any luck. I have the following model structure for my models/contact.py class BaseContact(AbstractUser): other_name = models.CharField(max_length=50, null=True, blank=True) contact_number = models.CharField(max_length=10, null=True, blank=True) email = models.EmailField(unique=True) postal_address = models.ForeignKey(location.Address, on_delete=models.CASCADE, null=True, blank=True) tax_id = models.CharField(max_length=11, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] class Meta: default_related_name = 'base' verbose_name = 'Contact' verbose_name_plural = 'Contacts' def get_absolute_url(self): return reverse("%s:detail-%s" % (str(type(self).__name__.lower()), str(type(self).__name__.lower())), kwargs={"pk": self.pk}) class Customer(BaseContact): class Meta: default_related_name = 'customer' class Supplier(BaseContact): class Meta: default_related_name = 'supplier' class Employee(BaseContact): class Meta: default_related_name = 'employee' verbose_name = 'Employee' verbose_name_plural = 'Employees' So my urls/contact.py is looking grim. from django.urls import path from main.views.contact import UpdateEmployeeView, DetailEmployeeView, CreateEmployeeView, DeleteEmployeeView from main.views.contact import UpdateSupplierView, DetailSupplierView, CreateSupplierView, DeleteSupplierView from main.views.contact import UpdateCustomerView, DetailCustomerView, CreateCustomerView, DeleteCustomerView urlpatterns = [ path('employee/create/', CreateEmployeeView.as_view(), name='create-employee'), path('employee/detail/<int:pk>', DetailEmployeeView.as_view(), name='detail-employee'), path('employee/update/<int:pk>', UpdateEmployeeView.as_view(), name='update-employee'), path('employee/delete/<int:pk>', DeleteEmployeeView.as_view(), name='delete-employee'), path('supplier/create/', … -
How to go to a page with single post from the news list
Can you help me with my project. I 'm trying to go from the page with all the news to a single post, but whatever i stay in page with all news. But if I write the address o in the address bar, everything works. Models.py class News(models.Model): title = models.CharField(max_length=1000, verbose_name='Название') slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='articles/', verbose_name='Фото') publish = models.DateTimeField(default=timezone.now, verbose_name='Дата публикации') author = models.ForeignKey(User, related_name='news', on_delete=models.CASCADE, verbose_name='Автор', null=True) text = models.TextField(verbose_name='Текст') tags = models.ManyToManyField(Tag, related_name='news', verbose_name='Тэг') created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') updated = models.DateTimeField(auto_now=True, verbose_name='Дата обнавления') status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='опубликован', verbose_name='Статус') class Meta: ordering = ('title',) verbose_name = 'Новости' verbose_name_plural = 'Новости' def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) Views.py def list_news(request): news = News.objects.all() return render(request, 'diplom/news/post.html', {'news': news}) def single_news(request, post_slug): post = get_object_or_404(News, slug=post_slug) return render(request, 'diplom/news/blog-single.html', {'post': post}) urls.py urlpatterns = [ path('news/', views.list_news, name='News'), path('post/<slug:post_slug>/', views.single_news, name='post') ] templates <div class="col-lg-4 col-md-6 grid-item"> {% for news in news %} <div class="blog-item large-item set-bg">{{ news.image }} <a href="{{post.get_absolute_url}}" methods="post" > <div class="categories">{{ news.title }}</div> <h5>{{ news.text| linebreaks|truncatechars:200 }}</h5> </a> <div> {{ news.publish }} {{ news.tag }} </div> </div> {%endfor%} </div> -
Is it possible to use the action tag in the form tag in ul or li?
I am trying to do web development with Django. It is recommended to use a form to be translated in its path while changing the language. In the proposed document, the language change function is given to the action attribute. Can I do this in ul or li? The suggested form is as follows: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> -
its showing a warring that sender is not accessed! and same with **kwargs and when I login as admin my profile page shows the details about the admin
"""I'm unable to access senders and **kwargs and this is my signals.py file and I guess is causing a bug that is when I login as admin its start showing admin details in my profile page too, please help me out as I'm new to Django""" from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance,**kwargs): instance.profile.save() -
How to automatically launch django web server by windows SYSTEM
I want to know if there's a way to have windows server 2019 automatically launch django's web server. I also want the launch to be performed at startup and by SYSTEM. I tried using batch scripts that launch manage.py from venv's python interpreter. When I launch the batch manually (i.e. double click) it works fine and dandy. But it appears that SYSTEM fails in running the script correctly when planning the task. I made SYSTEM launch another script at startup (a simple python script that creates a txt file from within its own venv) and it works. If the Django launch sceipt is launched by USER then it works. The problem is with the launching of django with SYSTEM. I've also tried streamlit and the result is the same. Do you have any Ideas? Sample batch script: cd path\of\managepyfile\ C:\path_to_venv\Scripts\python -m manage.py -
How to better format Django filter query for +1000 entries using SQLite3 database? (Expression tree is too large (maximum depth 1000))
The Django models I have are Component and Product. Components have Products as their Foreign Key. I am retrieving a search parameter from request.GET, called "components," that has a list of substrings that can belong to any Component. Based on the Components matched, I want to retrieve all Products that have this Component and return it back to the client. There are roughly 12000 Components and 3000 Products in my SQLite database I have been filtering out Products with the "|" operator for each of the Component's Product's id number, which works fine when searching for specific Component substrings, such as "Lactose" and "Bacterium." However, when I search for shorter substrings, such as "ac," I get the error: "OperationalError at /search, Expression tree is too large (maximum depth 1000)". From what I can understand, it's because the database is executing a multitude of union queries, and more than 1000 of those queries causes that error. I would like to know how to fix or workaround this error. Is there a better way to use Django's filter queries? Here is my models.py: from django.db import models class Product(models.Model): id_number = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=200) class Component(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name … -
Adding password protection with openpyxl in Django project
I tried to add password protection the excel file as shown below, but the protection is not happening, any body can tell us what is wrong here. def export_member_to_xlsx(request): user_queryset = User.objects.filter(is_staff=False) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-members.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = 'Members' worksheet.protection = WorkbookProtection(workbookPassword='password', lockStructure=True) columns = [ 'User', 'Email', 'First Name', 'Last Name', 'Member Since', 'Subscription Expiry', ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for member in user_queryset: row_num += 1 row = [ member.username, member.email, member.first_name, member.last_name, member.date_joined, member.subscriptions.current_period_end, ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response I tried the same protection code before workbook.save, but still it doesn't work -
empty formset CSS with Django Crispy Forms
I am trying to render a formset with crispy forms in Django, utilizing an add-more forms button. However I can't figure out how to apply the same CSS to the empty form as the original form. The only way I have been successful is creating a new empty form like this solution, but this adds in another <form> tag which is a problem that isn't covered in the solution. How can I apply CSS to the dynamically added formset? The below image is the expected result once I click the add more ingredients <button>: forms.py from .models import Recipe, RecipeIngredient from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Layout, Field class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['name', 'quantity', 'unit', 'description'] labels = { 'name': "Ingredient", "quantity:": "Ingredient Quantity", "unit": "Unit", "description:": "Ingredient Description"} def __init__(self, *args, **kwargs): super(RecipeIngredientForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-entryform' self.helper.form_class = 'form-inline' self.helper.layout = Layout( Div( Div(Field("name", placeholder="Chickpeas"), css_class='col-6 col-lg-4'), Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'), Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'), Div(Field("description", placeholder="No added salt tins"), css_class='col-12'), css_class="row", ), ) views.py: def recipe_create_view(request): form = RecipeForm(request.POST or None) RecipeIngredientFormset = formset_factory(RecipeIngredientForm, prefix="ingredient") formset = RecipeIngredientFormset(request.POST or None) context = { "form": … -
Iframe URL in Django? [duplicate]
I'm essentially trying to use an IFRAME on my django's html page to display another website inside of my current page. However nothing is popping up in the iframe, just the border. I think its due to the way django handles urls but im not for sure (Im fairly new to django). <iframe src="http://examplesite.com" style="border:0px #ffffff none;" name="myiFrame" scrolling="no" frameborder="1" marginheight="0px" marginwidth="0px" height="400px" width="600px" allowfullscreen></iframe> This is currently what im passing in my html file, but again, nothing is displaying inside of the iframe. Any ideas? -
Django custom AdminSite admin_view() not working, 404 error codes
admin.py class MyAdminSite(AdminSite): login_template = "admin/Slogin.html" index_template="admin/Shome.html" def get_urls(self): urls = super(MyAdminSite,self).get_urls() urls += [ url(r'^add_department/$', self.admin_view(self.add_department),name="add_department"), url(r'^add_equipment/$',self.admin_view(self.add_equipment),name="add_equipment"), url(r'^add_engineer/$',self.admin_view(self.add_engineer),name="add_engineer"), url(r'^engineer/<int:id>$',self.admin_view(self.update_engineer),name="update_engineer"), ] return urls def index(self,request): if request.method=="POST": engid=request.POST['eng_id'] noti=request.POST['notification'] ndate=date.today() ntime=datetime.now().strftime("%H:%M:%S") n=notification(engineer_id=engid,notification_text=noti,notification_date=ndate,notification_time=ntime) n.save() #messages.info(request,'Notification Send Successfully') department=Department.objects.all() engineer=User.objects.filter(is_staff=False) service=Service.objects.raw('''SELECT engineer_service.id as service_id,auth_user.username,engineer_service.service_date,engineer_equipment.id,engineer_equipment.equipment_name FROM engineer_service JOIN auth_user ON auth_user.id=engineer_service.equipment_id JOIN engineer_equipment ON engineer_equipment.id=engineer_service.equipment_id ORDER BY engineer_service.id DESC ''') equip=equipment.objects.all() noti=notification.objects.raw(''' SELECT * FROM engineer_notification Join auth_user on auth_user.id=engineer_notification.id order by engineer_notification.id DESC ''') activity=activity_tracker.objects.all().order_by('-id')[:5] context={ 'department':department, 'engineer':engineer, 'equipment':equip, 'service':service, 'activities':activity, 'notification':noti } return render(request,'admin/Shome.html',context) def add_department(self, request): if request.method=="POST": dept_name=request.POST['dept_name'] dept_id=request.POST['dept_id'] if dept_id!='0': dept=Department.objects.filter(id=dept_id).update(department_name=dept_name) messages.success(request,"Department Updated Successfully") else: d1=Department(department_name=dept_name) d1.save() messages.success(request,"Department Added Successfully") request.method="GET" return MyAdminSite.index(self,request) else: department=Department.objects.all() return render(request,"admin/add_department.html",{'department':department}) def add_equipment(self,request): # print("eq called") if request.method=="POST": equip_name=request.POST['name'] equip_doi=request.POST['doi'] dept_id=request.POST['dept_id'] equip_det=request.POST['details'] e=equipment(equipment_name=equip_name,department_id=dept_id,equipment_doi=equip_doi,equipment_details=equip_det) e.save() messages.success(request,"Equipment Added Successfully") request.method="GET" return MyAdminSite.index(self,request) else: equip=equipment.objects.all() department=Department.objects.all() return render(request,"admin/add_equipment.html",{'equip':equip,'department':department}) def add_engineer(self,request): print("add eng") engineer=User.objects.filter(is_staff=False) if request.method=="POST": firstname=request.POST['firstname'] lastname=request.POST['lastname'] username=request.POST['user_name'] pwd=request.POST['pwd'] if User.objects.filter(username=username).exists()==False: user=User.objects.create_user(username=username,first_name=firstname,last_name=lastname,password=pwd) user.save() messages.success(request,"Engineer Account Created Successfully") request.method="GET" return MyAdminSite.index(self,request) else: messages.warning(request,"User_name Already taken") return render(request,'admin/add_engineer.html',{'engineer':engineer}) else: return render(request,"admin/add_engineer.html",{'engineer':engineer}) def update_engineer(self,request,id): if request.method=="POST": username=request.POST['eng_username'] firstname=request.POST['eng_firstname'] lastname=request.POST['eng_lastname'] password=request.POST['eng_password'] user=User.objects.filter(username=username).update(first_name=firstname,last_name=lastname,password=password) messages.success(request,"Details Updated Sucessfully") request.method="GET" return MyAdminSite.index(self,request) else: user=User.objects.filter(id=id,is_staff=False) if user is not None: return render(request,'admin/update_engineer.html',{'user':user}) else: return render(request,'admin/Shome.html') admin_site = MyAdminSite() admin.site=admin_site admin.site.register(activity_tracker) admin.site.register(Service) admin.site.register(Department) admin.site.register(notification) admin.site.register(equipment) … -
How to extract the id of a Django formset in Javascript?
I have a doubt what happens is that I am trying to extract the id of a Django formset in Javascript, however when trying to do it I realized that this appears in Chrome DevTools: S.fn.init [[Prototype]]: Object (0) That is, nothing is happening, but it seems strange to me because when printing in the console I get the id name that I want what is happening and how can I extract its id and therefore the value?? calculate.js //the number of total forms is taken var formId="id_form-TOTAL_FORMS" var form_idx = document.getElementById('id_form-TOTAL_FORMS').value; console.log("el valor es:" + form_idx); var totalForms=parseInt($('#'+formId).val()); console.log("totalForms:"+totalForms) console.log(totalForms+1); //dynamic id are created var formset_quantity='id_form-'+form_idx+'-quantity'; var formset_unit_price='id_form-'+form_idx+'-unit_price'; console.log('formset quantity: '+formset_quantity); console.log('formset unit price: '+formset_unit_price); //the value of the one that contains the dynamic id is taken //This is when everything goes wrong because when printing in the console I get the error above, // as if that id does not exist(formset_quantity and formset_unit_price) or I am not creating it correctly var id_formset_quantity=document.getElementById('formset_quantity').value; var id_formset_unit_price=document.getElementById('formset_unit_price').value; var formset_total_price=document.getElementById('id_form-'+form_idx+'-total_price'); presupuestos-forms.html td id="parent_id_form-0-quantity"> <input type="number" name="form-0-quantity" class="form-control" id="id_form-0-quantity"> </td> <td id="parent_id_form-0-unit_price"> <input type="number" name="form-0-unit_price" class="form-control" id="id_form-0-unit_price"> </td> <td id="parent_id_form-0-total_price"> <input type="number" name="form-0-total_price" class="form-control" id="id_form-0-total_price"> </td> -
when and where & why need to use Django - signals
when and where & why need to use Django - signals . I didn't understand Django signals can anyone can help in details with sample example thank you.