Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save data to user models when using a resume parser in django
I am working on a website whereby users will be uploading resumes and a resume parser script will be run to get skills and save the skills to the profile of the user. I have managed to obtain the skills before saving the form but I cant save the extracted skills now. Anyone who can help with this issue will be highly appreciated. Here is my views file def homepage(request): if request.method == 'POST': # Resume.objects.all().delete() file_form = UploadResumeModelForm(request.POST, request.FILES, instance=request.user.profile) files = request.FILES.getlist('resume') resumes_data = [] if file_form.is_valid(): for file in files: try: # saving the file # resume = Profile(resume=file) resume = file_form.cleaned_data['resume'] # resume.save() # resume = profile_form.cleaned_data['resume'] # print(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) parser = ResumeParser(file.temporary_file_path()) # extracting resume entities # parser = ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) data = parser.get_extracted_data() resumes_data.append(data) resume.name = data.get('name') resume.email = data.get('email') resume.mobile_number = data.get('mobile_number') if data.get('degree') is not None: resume.education = ', '.join(data.get('degree')) else: resume.education = None resume.company_names = data.get('company_names') resume.college_name = data.get('college_name') resume.designation = data.get('designation') resume.total_experience = data.get('total_experience') if data.get('skills') is not None: resume.skills = ', '.join(data.get('skills')) else: resume.skills = None if data.get('experience') is not None: resume.experience = ', '.join(data.get('experience')) else: resume.experience = None # import … -
Problem loading large amount of geoJSON data to Leaflet map
I have geoJSON with more than 5000 objects containing various coordinates, but when they are displayed on the sitemap, the page either crashes or loads the objects for a very long time, but further interaction with the site is impossible. In index.html I have the following code: var mapOptions = { center: [14, 30], zoom: 7 } var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); map.addLayer(layer); var dataurl = '/locdata/'; fetch(dataurl) .then(function (resp) { return resp.json(); }) .then(function (data) { new L.GeoJSON(data, { onEachFeature: function (feature, layer) { layer.bindPopup(feature.properties.name); } }).addTo(map); The code for packing class objects into a JSON file contained in /locdata/ def loc_datasets(request): locations = serialize('geojson', Location.objects.all()) return HttpResponse(locations, content_type='json') The JSON looks like this: {"type": "GeometryCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"name": "00", "lon": 28.676971529668783, "lat": 60.02057178521224, "pk": "133811"}, "geometry": {"type": "Point", "coordinates": [28.676971529668783, 60.02057178521224]}}, {"type": "Feature", "properties": {"name": "41", "lon": 28.844832766965556, "lat": 60.02863347426495, "pk": "142975"}, "geometry": {"type": "Point", "coordinates": [28.844832766965556, 60.02863347426495]}}]} What is the reason that the coordinates cannot be displayed correctly on the Leaflet map on the user page? I'm working on Django, in which the data is displayed correctly in the admin panel. Thanks in … -
Using a React Template with Django (and React)
I am wondering how (or if it is even possible) to use a react template like this one: https://www.creative-tim.com/product/black-dashboard-react with an existing Django app. I have an app setup within a project like this ---project ---migrate.py ---project ---api (django app backend) ---models.py ---urls.py ---views.py ---..... ---frontend (react app) ---here Django a django app along with package.json, babel.config.json, webpack.config.js, and templates, static and src folders. I am wondering how I would integrate a template like the one linked above into this Django app. I am very new to React, I apologize if the question is explained poorly. I have tried replacing my folders and package.json files with the folders and files downloaded with the template. I couldn't get it to work properly. -
Start listening to kafka in a parallel stream when starting a django project
I want to run a file that listens to kafka in a parallel stream with a django project. My manage.py file import asyncio import os import sys import multiprocessing as mt from kafka.run_kafka import run_kafka def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() My run_kafka.py file uses Confluent Kafka Python import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'business_logic.settings') django.setup() import asyncio from business_logic.settings import KAFKA_CONF, TOPIC_PROD from kafka.kafka_consuners import KafkaConsumerBL async def run_kafka(): """ Запуск прослушивания Kafka на всех топиках на все ответы """ consumer = KafkaConsumerBL(KAFKA_CONF) consumer.indicate_topic([TOPIC_PROD]) await consumer.run_consumer(consumer) if __name__ == '__main__': asyncio.run(run_kafka()) I tried to solve the problem using the threading and multiprocessing libraries. After using any of the libraries, either the django project or kafka is launched. When using the multiprocessing library, one process is started, but not both manage.py ... if __name__ == '__main__': kafka_process = mt.Process(target=asyncio.run(run_kafka())) django_process = mt.Process(target=main()) kafka_process.start() django_process.start() kafka_process.join() django_process.join() … -
Django filter query using future date-time
How do I filter a query to contain only the objects that have a date-time field that holds a DateTime in the future? Here is my code that is not working: def matches(request): matches= Match.objects.all().filter(match_date_time > timezone.now() ) context = {'matches': matches} return render(request, 'bookie/matches.html', context) match_date_time is a model field in the Match model but I get an error that it's not defined. -
How can i import custom icons in leaflet Django webapp?
I am unable to import custom icons in my leaflet javascript file (Django webapp) var myicon=L.icon({ iconUrl:Url("icons/dead.svg"), iconSize:[30,40] }); I am trying this method but still unable to import..Any solution??? Please!!! -
Iterate a JSONfield corresponding to an object
The view receives an user request and then returns the corresponding object on the 'ControleProdutos' model db. views.py def relatorio_produtos(request): if request.method == 'POST': prod_json = ControleProduto.objects.get(pk = request.POST.get('periodo')) return render(request, 'selecao/historico-produtos.html', {'prod_json':prod_json}) else: return HttpResponseRedirect('/relatorios') model.py class ControleProduto(models.Model): periodo = models.DateTimeField(auto_now_add= True, verbose_name='Período') produtos = models.JSONField(verbose_name='Produtos') faturamento = models.FloatField(verbose_name='Faturamento') log_forma_pagamento = models.CharField(max_length=50, verbose_name='Forma de Pagamento') def __str__(self): return "{} {} {} {}".format(self.periodo, self.produtos, self.faturamento, self.log_forma_pagamento) def get_data(self): return{ 'periodo': self.periodo, 'produtos': self.produtos, 'faturamento': self.faturamento, 'log_forma_pagamento': self.log_forma_pagamento } class ListaProdutos(models.Model): nome_produto = models.CharField(max_length=50, verbose_name='Produto') quantidade_produto = models.IntegerField(verbose_name='Qntd.') vendido = models.IntegerField(verbose_name='Vendidos') data_adicao_prod= models.DateTimeField(auto_now_add= True ,verbose_name='Data de Adição') nota_produto = models.TextField(null=True, blank=True) custo = models.FloatField(verbose_name='Custo') tipo_produto = models.TextField(verbose_name='Tipo de Produto') def __str__(self): return "{} {} {} {} {} {} {} {}".format(self.nome_produto, self.quantidade_produto, self.vendido, self.data_adicao_prod, self.nota_produto, self.custo, self.tipo_produto) def get_data(self): return{ 'id': self.id, 'nome_produto': self.nome_produto, 'quantidade_produto': self.quantidade_produto, 'vendido': self.vendido, 'custo': self.custo, 'tipo_produto': self.tipo_produto, } Then, on the html file I'm using the for loop to iterate the JSONfield, but Django is indentifying the field as a string. html <p>{{ prod_json.periodo }}</p> <p>{{ prod_json.produtos }}</p> <p>{{ prod_json.faturamento }}</p> <p>{{ prod_json.log_forma_pagamento }}</p> <table> <thead> <tr> <th>ID</th> <th>Produto</th> <th>Quantidade Vendida</th> </tr> </thead> {% for prod in prod_json.produtos %} <tbody> <tr> <td>{{prod.pk}}</td> </tr> </tbody> {% endfor %} … -
read more button is not working on my blog post
enter image description here when i press read more to read full article ,is not opening. please am new to django where can i fixed the error i change my url as below from . import views from django.urls import path urlpatterns = [ path('', views.postlist.as_view(), name="home"), path('<slug:slug>/', views.postlist.as_view(), name="post_detail"), #path('<slug:slug>/', views.DetailView.as_view(), name="post_detail"), ] is not still working -
Docker image url validation for django
I want to get docker image URL from the user but URLs can't be acceptable with models.URLField() in django.For example, this URL: hub.something.com/nginx:1.21, got an error.How can fix it? -
Get hierarchical data
I have a db table id name parent id 1 A None 2 B 1 3 C 2 So there are many parents (parent id none) with arbitrary number of children and arbitrary depth. I want to write a django db query (recursive mysql db queries is not an option) so i can print the entire nested structure all the way to leaf element like so for a given id. What is the best way to achieve this? A --B ----C ----D --P ----Q Only solution i could think of is to query the db initially like so table.Object.filter(Q(id=id) | Q(parent_id=id)) to get the parent and its children. Iterate over children to go dfs and query db in the dfs method for nested children until it goes to the leaf element. I am trying to figure out if django has additional tools that could some how get the entire hierarchy with a few queries as possible (ideally one) -
Django static files not loading/working with no error signs
Unable to load static files, looked around the internet, but the solutions aren't working for me. Pls help. I tried moving around the static folder changing its place, tried playing around in settings.py, but nothing seems to fix it, i don't get 404 in the terminal but instead "GET / HTTP/1.1" 200 4441 All i am trying to do is change the backround color to confirm it if works body{ backround-color: blue; } like this i mean Any help would be greatly appreciated Here is my main.html where i load static: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Mutuals</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'styles/main.css' %}"> </head> Static folder location Settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] -
Cannot import django-smart-selects
I wanted to use the django smart select library to create related dropdowns. I did everything as indicated in the library documentation, but an error occurs: import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6] Even when I enter "import ..." the library itself already glows gray, as if it does not find it. This is what my INSTALLED_APPS in settings.py looks like: INSTALLED_APPS = [ 'routes_form.apps.RoutesFormConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'smart_selects', ] USE_DJANGO_JQUERY = True This is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('form/', include('routes_form.urls')), path('admin/', admin.site.urls), path(r'^chaining/', include('smart_selects.urls')), ] ...and my model.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey I tried to find a solution to the problem, looked for possible options. That is why I already changed from `JQUERY_URL = True` to `USE_DJANGO_JQUERY = True`. Errors (six) I did not take off. I have only this...: `import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6]` I would be incredibly grateful even for trying to help. -
HOW DO I MAKE A TEACHER VIEW ASSIGNMENTS OF STUDENTS BELONGING TO HIS/HER CLASS ONLY?
Hi Guys i need help im developing a django software whereby students submit assignments online on a school platform ,How do i make a teacher view assignments for his specific claass only Right now my software is submiting assignments , and viewing all the assignments even those of students not belonging to his/her class .So i expect the software to view only assignments of students belonging to the class of logged in teacher -
can't get the back end data when I run a react app from other device
I have a project with react on the front and django/python and postgres on the back Everything goes ok on the computer, but if I run it from another device, in the same network, the data can’t be loaded, it says axios network error I found my Ip with ipconfig, suppose it's 192.xxx.xxx.xxx, then I set in the mobile device http:// 192.xxx.xxx.xxx:3000, it runs the application but the data can't be found there, it says AxiosError: Network Error My computer recognizes the wifi network 2.4, then I connect the phone to the 2.4 network In the axios call, I set the address as: const response = await axios.get( `http://127.0.0.1:8000/api/v1/whole_menu/${restaurantId}` ); (I’m not using localhost) But I still get the network error in the phone, but in the computer, everything is ok What could it be? Thanks in advance Rafael -
ensure_csrf_cookie method decorator not setting CSRF token in browser cookies tab
I'm working on a project using Django as API backend (hosted on localhost:8000) and React (hosted on localhost:3000) as frontend. My plan is to host them on different servers in production as well. I'm currently trying to set the CSRF token in the browser cookies tab using the "ensure_csrf_cookie" method decorator. While the javascript API call seems to work and returns the response, no cookie is set in my cookie tab (tested in different browsers). However, the weird thing is that when I type in the CSRF token URL directly in the browser, the cookie is set. This leads me to believe it's not working due to some cross-origin issues. So I've tried many different settings in my settings.py file without success. Django View: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response ({ "success": "CSRF cookie set"}) React: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } async function … -
DRF tries to create User object when used in nested serializer
DRF docs says that "By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be save."<< In general this is true except for one case. When User class is a nested object in serializer. Use case is to add existing user to newly created organization. Consider my simple example where I noticed that issue: views.py class UserOrganizationViewSet(viewsets.ModelViewSet): # authentication_classes = (JwtAuthentication, SessionAuthentication) # permission_classes = (permissions.JWT_RESTRICTED_APPLICATION_OR_USER_ACCESS,) serializer_class = UserOrganizationSerializer queryset = UserOrganization.objects.all() models.py: class UserOrganization(models.Model): name = models.CharField(max_length=256) users = models.ManyToManyField(User, blank=True, related_name="user_organizations", through='OrganizationMember') def __str__(self): return self.name class OrganizationMember(models.Model): organization = models.ForeignKey(UserOrganization, on_delete=CASCADE) user = models.ForeignKey(User, on_delete=CASCADE) joined = AutoCreatedField(_('joined')) serializers.py: First version - User class has its own simple serializer and it is used as nested serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['username'] class UserOrganizationSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, required=False) class Meta: model = UserOrganization fields = ['id', 'name', 'users'] read_only_fields = ['id'] Is this case I am able to fetch data via GET method (Organization created through admin panel): But when I am trying to create organization I am … -
i can't add domain name to server
i create Django one click drophlet on Digitalocean. i configure my website and i want add domain name. i configure my nginx and i add to server domain name . i also add nameservers on my domain registrant and configure domain name on digitalocean but still didn't work. here is my configuration. upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name recourse.ge www.recourse.ge; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0;} } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } I add nameservers to my domain registrant. i add also A record to my digitalocean domain name. i configure nginx and add my domain name to nginx configuration and i add in settings.py Allowed host my domain name. -
How do I use Django's built in password reset function?
I am using the following code to use Django's built in password reset functions. Everything seems to work for some email addresses but not for others. I know for sure that I am having difficulties with @btopenworld.com addresses. I have read other places saying that the user accounts need to have functional passwords set up. I have tried the same user account with different passwords (some reset emails get delivered, some do not). Any ideas on how to get this working more consistently? In my login template file: <div class="mt-4"> <div class="d-flex justify-content-center login_container"> <a href ="{% url 'reset_password' %}" class="btn btn-warning" >Create / Reset Password</a> In my urls.py file: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="accounts/password_reset.html"), name="reset_password"), In the password_reset.html file: <p>Enter the email address used to create your account, and we’ll email instructions for setting a new password.</p> <form method="post"> {% csrf_token %} {{form}} <input type="Submit" name="Send email"> </form> -
How to call a function after full save of an object in Django
Currently in my project I use different receivers with the post_save signal successfully. However, in one of them I need to perform an update assuming it has already been done, however since the post_save request is fired inside the save function, that updated data is still not reflected in a queryset request. In this case I can use exclude to ignore the data from the present record but I would like to know a cleaner way to do this within the Django schema without resorting to Celery, threading, etc. Any suggestions? -
using rest_framework_simplejwt.authentication - token expire after short time, and then the user have to login again
I new in WEB world and Authentication, and I got some problems. I try to set JWT Authentication with Django and React, but even after I set this in django: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=20) } In the frontend side (my react app), I automatically disconnect after something like 30 min's, and then I have to login again (and I set life time to 10 days!). So im not sure what going there, and why the default value to 'ACCESS_TOKEN_LIFETIME' is 5 min? who want to keep login and login again every 5 minutes? I think I don't understand something or miss something. I've given up already and would appreciate some help - or some diffrent way to do Authentication with django-react app. Just in case, here more configurations that are related: DEFAULTS = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": settings.SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "JTI_CLAIM": "jti", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } … -
Using some html-to-pdf tool to get invoice.pdf
I want to use other libraries than pdfkit since wkhtmltopdf doesn't work for heroku. I want to replace some of these lines for usage with other libraries. pls guide me! as far as I know, only the generatePDF part needs tweaking. views.py: from django.shortcuts import render, redirect, get_object_or_404, reverse from django.template.loader import get_template from django.http import HttpResponse from django.views import View from .models import LineItem, Invoice from .forms import LineItemFormset, InvoiceForm import pdfkit class InvoiceListView(View): def get(self, *args, **kwargs): invoices = Invoice.objects.all() context = { "invoices": invoices, } return render(self.request, 'invoice/invoice-list.html', context) def post(self, request): # import pdb;pdb.set_trace() invoice_ids = request.POST.getlist("invoice_id") invoice_ids = list(map(int, invoice_ids)) update_status_for_invoices = int(request.POST['status']) invoices = Invoice.objects.filter(id__in=invoice_ids) # import pdb;pdb.set_trace() if update_status_for_invoices == 0: invoices.update(status=False) else: invoices.update(status=True) return redirect('invoice:invoice-list') def createInvoice(request): """ Invoice Generator page it will have Functionality to create new invoices, this will be protected view, only admin has the authority to read and make changes here. """ heading_message = 'Formset Demo' if request.method == 'GET': formset = LineItemFormset(request.GET or None) form = InvoiceForm(request.GET or None) elif request.method == 'POST': formset = LineItemFormset(request.POST) form = InvoiceForm(request.POST) if form.is_valid(): invoice = Invoice.objects.create(customer=form.data["customer"], customer_email=form.data["customer_email"], billing_address=form.data["billing_address"], date=form.data["date"], due_date=form.data["due_date"], message=form.data["message"], ) # invoice.save() if formset.is_valid(): # import pdb;pdb.set_trace() … -
Add user to group in signal post_save
I want to add a user to a group after the user object is saved. Each user has a user type corresponding to the group the user belongs to. For example, if the user_type is 2, then the user belongs to Group_3, and so on. This is my code: class User(AbstractBaseUser, PermissionsMixin): """ Custom user model """ USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) email = models.EmailField( ("Email Address"), max_length=255, unique=True, help_text="Ex: example@example.com", ) eec = models.ForeignKey( EEC, on_delete=models.CASCADE, null=True, related_name='eec',blank=True) is_staff = models.BooleanField(("Staff status"), default=False) is_active = models.BooleanField(("Active"), default=True) date_joined = models.DateTimeField(("Date Joined"), auto_now_add=True) last_updated = models.DateTimeField(_("Last Updated"), auto_now=True) user_type = models.IntegerField(default=1, choices=USER_TYPE) lastName = models.CharField(default='', max_length=250) firstName = models.CharField(default='', max_length=250) objects = UserManager() USERNAME_FIELD = "email" def __str__(self): return self.email class Teacher(models.Model): admin = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 1: Admin.objects.create(admin=instance) if instance.user_type == 2: try: Teacher.objects.create(admin=instance) g1 = Group.objects.get(name='teacher') instance.groups.add(g1) except: print("Exception") if instance.user_type == 3: Student.objects.create(admin=instance) Basically, when I save the user model with a user type of 2, the group does not get updated -
how to delete an object in modelViewset in DRF?
I am doing a project in DRF and using modelviewset, my object has two boolean fields and two users as foreign keys, now i want to show the object only to those users and if both of them set their correspond's boolean attribute to True then the object will be deleted i'm handling the logic of some code in custompermissions.py but i dont know if to handle the deletion of the object in there too or in the view, and since i need to verify if the current user is either one of the users i have some logic to do, i dont know what type of request i should permit also becuase DELETE will delete the object and i need to delete only in case both values are true, and i can do it in a get but then i will have to spllit the show and delete into 2 diffrent routs. can someone recommend what is best for me to do? i want to show and delete an object in a spcifec case -
How to create dynamic delete formset?
I have a formset in the html. I added a addMore button to add a form. Now i want to create dynamically remove button in html, but i am lack experience of js with DOM. How to make delete button dynamically using js? html {% block isi %} <!-- INFORMASI ACARA --> <div class="notification is-light p-1 has-text-centered mt-4"> INFORMASI ACARA </div> <div class="columns is-multiline"> {% if formset6 %} {{ formset6.management_form }} <div class="column is-12"> <div id="ingredient-form-list6"> {% for form in formset6 %} <div class="ingredient-form6 mb-3"> {% for field in form.visible_fields %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} <p class="help is-danger">{{ error }}</p> {% endfor %} {% endfor %} <div class="is-hidden"> {% for field in form.hidden_fields %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} <p class="help is-danger">{{ error }}</p> {% endfor %} {% endfor %} </div> </div> {% endfor %} </div> </div> <div id="empty-form6" class="is-hidden">{{ formset6.empty_form }}</div> {% endif %} </div> <button id="add-more6" type="button" class="button is-small is-outlined pd-1 mb-4">Tambah</button> {% endblock %} js const addMoreBtn6 = document.getElementById('add-more6') const totalNewForms6 = document.getElementById('id_acara-TOTAL_FORMS') if (addMoreBtn6) { addMoreBtn6.addEventListener('click', add_new_form6) } function add_new_form6(event) { if (event) { event.preventDefault() } const currentIngredientForms6 = document.getElementsByClassName('ingredient-form6') const … -
Saving a JSON object as the entire model in DJANGO
I want to save the information that my front sends me in the database (I receive a JSON), the problem is that there are foreign keys in the model and these may or may not be filled and when I try to save some data with the empty FK I receive the 'matching' error query does not exist.' or other errors related to the 'key' not existing in the database. What occurs to me is to remove it from the front before it is sent to DJANGO and save the object as such but I don't know if it's possible, if you also have another solution I would greatly appreciate it Add def agregarIniciativa(request): if request.user.is_authenticated: if request.method =='POST': try: data = json.load(request) iniciativa = Iniciativa( iniciativa = data['nombre'], fecha_inicio = data['fecha_inicio'], fecha_final = data['fecha_final'], canal=Canales.objects.get(id=int(data['canal'])), territorio = data['territorios'], audiencia = AudienciaDirigida.objects.get(id=int(data['audiencia'])), bigbet = BigBet.objects.get(id=int(data['bigBet'])), marca = Marcas.objects.get(id=int(data['marca'])), fgp = float(data['fgp']), objetivo = data['objetivo'], call2action = data['call2Action'], dialogo_valor = data['dialogoValor'], cobertura = data['cobertura'], volumen_datos = data['volumen'], kpi_medicion = data['kpi'], inversion_datos = data['inversion'], beneficio_datos = data['beneficio'], volumen_total = int(data['total_vol']), inversion_total = int(data['total_inv']), beneficio_total = int(data['total_ben']), marcas = data['marcas'], fgp_datos = data['fgpDatos'] ) iniciativa.save() return JsonResponse({ "msg": "Guardado" }) except Exception as …