Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The b-button is not displayed in the b-table VueJs
Im starting at Vue Js, my problem is that my b-button is not shown in my table and I don't understand why. Here is my HTML code: <div id="listlocales"> <div class="overflow-auto"> <b-button size ="sm" href="{% url 'newLocal'}" variant="outline-primary"> Nuevo Local</b-button> <br></br> <b-table id="my-table" striped responsive="sm" :items="items" :fields="fields" :per-page="recordsPerPage" :current-page="currentPage"> <template #cell(actions)='data'> <b-button size="sm" variant="primary" @click="getLocales()"> Editar </b-button> <b-button size="sm" variant="danger" href="{% url 'newLocal' %}"> Eliminar </b-button> </template> </b-table> <b-pagination v-model="currentPage" :total-rows="totalPages" :per-page="recordsPerPage" aria-controls="my-table" ></b-pagination> </div> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script> <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> And here is my script Vue code: <script> const listloc = new Vue({ el: '#listlocales', data: { items: [], currentPage: 1, totalPages: 0, recordsPerPage: 10, isLoading: false, fields: [ { key: 'id', label: 'ID' }, { key: 'descripcion', label: 'Descripcion' }, { key: 'clave', label: 'Clave' }, { key: 'responsable', label: 'Responsable' }, { key: 'actions', label: ''} ] }, ... }); </script> </body> </html> I tried to use v-slot instead cell but isn't working anyway... Can someone help me for solving this issue. -
Image not visible despite correct syntax
I am doing CRUD using serializers,and one of the data is uploading the image,the problem is that despite the correct syntax,the image is not getting uploaded below is the product_list image html code {% if result.image %} <td> <img src="{{result.image.url}}" alt="no image"> </td> {% endif %} below are the functions and additions made in settings settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' functions and model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) def filepath(request,filename): old_filename = filename timeNow = datetime.datetime.now().start('%Y%m%d%H:%M:%S') filename = "%s%s" % (timeNow,old_filename) return os.path.join('uploads/',filename) where am I going wrong in the code? -
How to add Authenticate Middleware JWT django REST?
I'm a begginer in using Django and REST. And in my project I have to add custom JWT auth. I've tried to generate it like this inside of User model: class User(AbstractUser): .... def _generate_jwt_token(self): dt = datetime.datetime.now() + datetime.timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.encode("windows-1252").decode("utf-8") In my views I did class LoginAPIView(APIView): def post(self, request): ... response = Response() response.set_cookie(key="jwt", value=user.token, httponly=True) ... return response And class CurrentUserAPIView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('This user is unauthenticated') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except: msg = 'Invalid authentication. Could not decode token.' raise AuthenticationFailed(msg) try: user = User.objects.get(pk=payload['id']) except User.DoesNotExist: msg = 'No user matching this token was found.' raise AuthenticationFailed(msg) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) But I think this logic has to be inside a middleware. Could you give me an advice how can I rewrite this code. Thank you so much! -
Django URLfield st
Trying to build Django Models with Django rest_framework serializers. Models should store list of URLs searched by a user and the serializer should help return combination of those urls. Got it to work based on documentation and two answered questions (first, second), but cannot figured how to get a desired formatting: unpack a list of dictionaries inside returned rest_framework response. Current api output looks like that: What I would want is for links to be just a list of urls instead of dictionaries. models.py (short version): class User(AbstractUser): pass class Combo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches') updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) class ComboLink(models.Model): combo = models.ForeignKey('Combo', on_delete=models.CASCADE, related_name='links') link = models.URLField(null=True, blank=True) serializers.py: class ComboLinkSerializer(ModelSerializer): class Meta: model = ComboLink fields = ['link'] class ComboSerializer(ModelSerializer): links = ComboLinkSerializer(many=True) class Meta: model = Combo fields = ['user', 'id', 'created', 'links'] -
my custom django_admin command got error AttributeError: object has no attribute 'title'
So I am working on RSS Feed on Django. Whenever I try to run the custom command file (startjobs.py) in command prompt, the error appeared: Job "fetch_talkpython_posts" raised an exception Traceback (most recent call last): File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 156, in __getattr__ return self.__getitem__(key) File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 113, in __getitem__ return dict.__getitem__(self, key) KeyError: 'title' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\xxx\xxx\anaconda3\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\xxx\xxx\django_project\pyagg\content_aggregator\news\management\commands\startjobs.py", line 39, in fetch_talkpython_posts save_new_posts(_feed) File "C:\xxx\xxx\django_project\pyagg\content_aggregator\news\management\commands\startjobs.py", line 18, in save_new_posts feed_title = feed.channel.title File "C:\xxx\xxx\anaconda3\lib\site-packages\feedparser\util.py", line 158, in __getattr__ raise AttributeError("object has no attribute '%s'" % key) AttributeError: object has no attribute 'title' I couldn't figure out why this error occured and what's wrong with fetch_talkpython_posts(). Any help would be appreciated. my custom command file startjobs.py: import logging from django.conf import settings from django.core.management.base import BaseCommand import feedparser from dateutil import parser from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.cron import CronTrigger from django_apscheduler.jobstores import DjangoJobStore from django_apscheduler.models import DjangoJobExecution from news.models import Post logger = logging.getLogger(__name__) def save_new_posts(feed): feed_title = feed.channel.title feed_image = feed.channel.image["href"] for item in feed.entries: if not Post.objects.filter(link=item.link).exists(): post = Post( title=item.title, description=item.description, pubdate=parser.parse(item.published), link=item.link, image=feed_image, #p_title=feed_title, … -
Input value Set using jquery's selector does not post
there's this issue where I created a form using django. The form contains two charfields for name and address, and two datetimefields one for a start_date and the other for a stop_date. Finally there are two radio buttons, such that: when the first is checked, the start_date field's value is set to date.now() using jquery's selector when the second radio button is checked, the start_date and stop_date fields are disabled, still using jquery's selector. The above code works well. However, when the start_date's value is successfully set, I have to post the form data using jquery ajax post method to a django view, the start_date's value is not posted at all, while the other field values are. I don't know how to go about this issue. Here's my code template.html {% extends 'base.html' %} <div class="center"> <form action="" invalidate> {% crispy form form.helper %} </form> </div> script.js $('input:radio').click(function){ if ($(this).val() === '1'){ var start_date = new Date(); $('#id_start_date').val(start_date); } else if ($(this).val() === '0'){ document.getElementById('id_stop_date').disabled = true; document.getElementById('id_start_date').disabled = true; } } $("form").on("submit", function (e){ var name = $("#id_name"); var type = $("id_type"); var start_date = $("id_start_date"); var stop_date = $("id_stop_date"); $.ajax({ type:"POST", url:"{% url 'postAccount' %}", data:{ csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').Val(), … -
How to print variable of nested for loop in django?
I want print values from database to html page Here is my code:enter image description here instead of writing {{i.id}} or {{i.date}} I want id and date to come from a list called colname so the first loop will contain object (i.e. i) from database and the second loop contains all the columns name (i.e. j) and I want to print {{i.j}} but I am not able to get any value -
How to write a view to add a user to a group in Django rest framework
I want to write a view that can add my users to a group Please help, thank you -
django.db.utils.IntegrityError: NOT NULL constraint failed: new_carts_cartitem.cart_id
how to handle this error? django.db.utils.IntegrityError: NOT NULL constraint failed:new_carts_cartitem.cart_id When I add "orders" app, this error occurs. My Project: [1]: https://github.com/chickenhihi/GreatCart Help me, please ! Thank you very much... -
How can I make two user models, "Customer" and "Dealer" with different table in django
I'm New in Django and I'm working on a project in which I want to make separate Login, Logout, Verification and Reset Password apis with JWT I'm trying to get different tables so that if one tries to login in Dealer Id from Customer id, then it won't accept it and so the person has to register on Dealer api too My models.py is like this from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from rest_framework_simplejwt.tokens import RefreshToken class UserManager(BaseUserManager): def create_user(self, username, email, mobile_number, account_role, account_type, role, address, state, city, pincode, password = None): user = self.model(username = username, email = self.normalize_email(email), mobile_number = mobile_number, account_role = account_role, account_type = account_type, role = role, address = address, state = state, city = city, pincode = pincode) user.set_password(password) user.save() return user def create_superuser(self, username, email, mobile_number, account_role, account_type, role, address, state, city, pincode, password = None): if password is None: raise TypeError('Password Should Not Be None') user = self.create_user(username, email, password, mobile_number, account_role, account_type, role, address, state, city, pincode) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) mobile_number = models.CharField(max_length=12) account_role = models.CharField(max_length=50, default='Customer') … -
How to implement OpenID Connect with multiple providers in Django?
I'm trying to implement multiple SSO (OpenID Connect) logins in my application, besides the regular one. The current provider requests are Azure and Okta, but there will be more. For every bigger customer using my application, I want to be able to enable them a custom SSO login that they can setup in the admin panel. All the libraries I've tried using for this are either using settings.py and local django authentication, or they are deprecated. The flow is like this: User chooses their company and SSO login button -> Gets redirected to login -> I send the client id, secret etc. (which they entered in the admin panel when registering an sso connection) -> I get a token in return with the users name and email -> with this info (email) I find the already existing user in my local database and log him in -
Why am I facing "An error occured" after adding "'social_django'," in INSTALLED_APPS section of settings.py?
I'm trying to implement oauth with Twitter login. I noticed that I get error back if I add this line in INSTALLED_APPS section of settings.py 'social_django', Why am I getting this error on nginx? nginx error page An error occurred. Sorry, the page you are looking for is currently unavailable. Please try again later. If you are the system administrator of this resource then you should check the error log for details. Faithfully yours, nginx. settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'user_auth', 'social_django', ] ... My project works fine without this 'social_django', var/log/nginx/error.log 2022/07/13 17:39:29 [error] 1034#1034: *46 connect() failed (111: Connection refused) while connecting to upstream, client: ***.***.***.***, server: ***.***.***.***, request: "GET /post-1/ HTTP/1.1", upstream: "http://127.0.0.1:8000/post-1/", host: "***.***.***.***", referrer: "http://***.***.***.***" -
Need help writing a test case in Django
def create_reset_email( request: Any, user: Any, encoded_pk: str, token: str ) -> dict: current_site = get_current_site(request).domain reset_url = reverse( "reset-password", kwargs={"encoded_pk": encoded_pk, "token": token}, ) absurl = f"http://{current_site}{reset_url}" body = {"user": user, "link": absurl} data = { "subject": "YOUR PASSWORD RESET LINK", "body": body, "recipient": user.email, } return data -
How to run migrations for a specific tenant/schema in Django multi-tenant framework?
The tenant_command was not working properly according to my requirements. So, I found out this solution after tweaking the command below python3 manage.py tenant_command migrate --schema=schema_name -
django-push-notifications in Django Rest Framework
I'm trying to use django-push-notifications library in my Django REST backend project. I have used Firebase Cloud Messaging. Here is the implementation; settings.py PUSH_NOTIFICATIONS_SETTINGS = { "FCM_API_KEY": "private key from FCM app" } views.py user, created = User.objects.get_or_create(email=email, username=username) if created: GCMDevice.objects.create(registration_id="token", cloud_message_type="FCM", user=user) models.py @receiver(post_save, sender=Action) def create_new_action(sender, instance, created, **kwargs): if created: devices = GCMDevice.objects.filter(Q(user=instance.admin)|Q(user__in=instance.users.all())) msg = "New action is created in %s" % instance.name devices.send_message(msg) My question is what should registration_id be while I'm creating the GCMDevice object for each registered user? -
Dealing with the environment url in the "build" version of react
I'm trying to deploy a react-django app to production using digitalocean droplet. I have a file where I check for the current environment (development or production), and based on the current environment assign the appropriate url to use to connect to the django backend like so: export const server = enviroment ? "http://localhost:8000" : "domain-name.com"; My app is working perfectly both on development and production modes in local system (I temporarily still used http://localhost:8000 in place of domain-name.com). But I observed something rather strange. It's the fact that when I tried to access the site (still in my local computer) with "127.0.0.1:8000" ON THE BROWSER, the page is blank with a console error "No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' ....". When I changed it back to "http://localhost:8000", everything was back working. My worry is isn't 127.0.0.1:8000 the same as http://localhost:8000? From this I conclude that whatever you have in the domain-name.com place when you build your react frontend is exactly what will be used. Like I said, I'm trying to deploy to a digital ocean droplet, and I plan to install ssl certificate so … -
Display users bookings when they are logged in
I am hoping someone can help me with something, I am new to Django and am currently putting together a restaurant booking system application. I have a lot of what I want to do done already but what I now want is for all a users bookings to appear in a "My Bookings" page when they are logged into their accounts. I want to give people the option to edit or cancel bookings if needed. Can anyone guide me in the right direction in terms of making just the users bookings appear when they log in? Thanks -
service refers to undefined volume
I want to share temp files between Django project and celery worker (it works with TemporaryUploadedFiles, so I want to have access to these files from celery worker to manage them). I've read about shared volumes, so I tried to imlement it in my docker-compose file and run it, but the command gave me this error: $ docker compose up --build service "web" refers to undefined volume shared_web_volume/: invalid compose project And sometimes "web" replace with "celery", so both celery and django have no access to this volume. Here is my docker-compose.yml file: volumes: shared_web_volume: postgres_data: services: db: image: postgres:12.0-alpine ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: context: ./MoreEnergy dockerfile: Dockerfile entrypoint: sh ./entrypoint.sh command: python manage.py runserver 0.0.0.0:8000 volumes: - "shared_web_volume/:/MoreEnergy/" ports: - 1337:8000 env_file: - ./.env depends_on: - db celery: build: context: ./MoreEnergy dockerfile: Dockerfile entrypoint: sh ./entrypoint.sh command: celery -A MoreEnergy worker --loglevel=info volumes: - "shared_web_volume/:/MoreEnergy/" env_file: - ./.env depends_on: - web - redis redis: image: redis:5-alpine What am I doing wrong? Upd: temp dir is my project folder (I've set it with FILE_UPLOAD_TEMP_DIR variable in settings file), so I don't need to make one more volume only for shared temp files (If … -
Group Django error logging by user instead of errors
Under Django daily jobs, for integrity check, is there a way to log the errors by user instead of all errors? To prevent a single user from spamming the system with errors. Thanks! -
How to disable field from View on Django?
I am struggling trying to disable it, but I am using the same form for two different views, and on one view I need to disable or readonly a field, how can I reach this? I reach this so far on VIEWS.py obj = ModelUpdate.objects.first() field_object = ModelUpdate._meta.get_field('myfield') field_value = getattr(obj, field_object.attname) Thank you -
how to create model instance in drf serializers
I am new to DRF. I want to get saved the model ... Thank in advance. In models.py, PackageDetails and PhysicalDetail have foreignkey relationship to Member my serializers.py is as follows from rest_framework import serializers from .models import Member, PackageDetails, PhysicalDetail class PackageDetailsSerializer(serializers.ModelSerializer): is_expired = serializers.SerializerMethodField() members_expiry_date = serializers.SerializerMethodField() class Meta: model = PackageDetails exclude = ['id'] extra_fields = ['is_expired', 'members_expiry_date'] def get_is_expired(self, instance): return instance.is_expired def get_members_expiry_date(self, instance): return instance.members_expiry_date class PhysicalDetailSerializer(serializers.ModelSerializer): class Meta: model = PhysicalDetail exclude = ['id'] class MemberSerializer(serializers.ModelSerializer): physical_details = PhysicalDetailSerializer(many=True) package_details = PackageDetailsSerializer(many=True) class Meta: model = Member fields = '__all__' extra_fields = ['physical_details', 'package_details'] def create(self, validated_data): physical_detail_data = validated_data.pop("physical_details") package_detail_data = validated_data.pop("package_details") member = Member.objects.create(**validated_data) PhysicalDetail.objects.create(member=member, **physical_detail_data) PackageDetails.objects.create(member=member, **package_detail_data) return member views.py : class MemberViewset(viewsets.ModelViewSet): queryset = Member.objects.all() serializer_class = MemberSerializer class PackageDetailViewset(viewsets.ModelViewSet): queryset = PackageDetails.objects.all() serializer_class = PackageDetailsSerializer class PhysicalDetailViewset(viewsets.ModelViewSet): queryset = PhysicalDetail.objects.all() serializer_class = PhysicalDetailSerializer In GET request it worked well.. but in POST request with the same json format it responses the following: { "physical_details": [ "This field is required." ], "package_details": [ "This field is required." ] } I've provided the fields.. so why this happening.. -
Django 4 update form fields dynamically using HTMX
I developed a Django application in which i have a form with some fields. Depending on the input additional fields are displayed are hidden. Now everything worked quit fine in Django 3.2.14 since the update in Django 4.0.6 it didn't worked anymore. I first build a form, where if a "field_rule_display" exists the field widget is set as "HiddenInput". class AnalysisForm(forms.Form): def __init__(self, analysis_form_template: AnalysisFormTemplate, disable_required: bool, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout() self.helper.add_input(Submit("submit", _("Evaluate"), css_class="btn-primary btn-lg")) analysis_field_queryset = analysis_form_template.analysis_fields analysis_form_url = reverse("analysis_form", args=(analysis_form_template.id,)) for field in analysis_field_queryset.all(): htmx_dictionary = _htmx_dictionary(analysis_form_url, field) self.fields[field.name_for_formula] = _get_field_by_type( field, htmx_dictionary, analysis_form_template, self.data ) self.fields[field.name_for_formula].empty_values = empty_values() self.helper.layout.fields.append( Div(Field(field.name_for_formula), css_class=AnalysisFieldKind(field.kind).name) ) if field.field_rule_display is not None and disable_required is False: self.fields[field.name_for_formula].widget = forms.HiddenInput() self.fields[field.name_for_formula].widget.attrs["disabled"] = True if disable_required: self.fields[field.name_for_formula].required = False After the user enters a specific input into the form, htmx will send a request and i rebuild the form with the new fields. And here the problem starts, even if i update my field in the "self.fields" Django does not render the update and my form field is still hidden. if field.field_rule_display is not None: evaluated_result_display = self._evaluated_formula( field, analysis_form_template, field.field_rule_display, field.field_rule_display.formula, cleaned_data, ) if evaluated_result_display: field_type = … -
Image not visible despite adding every neccessary detail
I am doing CRUD using serializers(as it is my task) where one of the thing I need to insert is an image.I have added everything neccesary for image to be displayed ,the image added is not visible as shown below below are the models,functions,additions made in settings and html urls if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR,'media/') MEDIA_URL = '/media/' models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) def filepath(request,filename): old_filename = filename timeNow = datetime.datetime.now().start('%Y%m%d%H:%M:%S') filename = "%s%s" % (timeNow,old_filename) return os.path.join('uploads/',filename) insert function def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['image'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = … -
How to make a query to a specific object DJANGO does not work for me,
the idea is that in the django admin, do an action that generates a pdf, I already have the pdf format and the records are shown to me, but I only want to choose a specific record and that the data of that object appears in the Pdf. `#MODELOS class SalidaDotaciónPersonal(models.Model): solicitado_por=models.CharField(max_length=40,verbose_name="Solicitado por:") unidad=models.CharField(max_length=24,verbose_name="Unidad", default="Arco Iris") fecha = models.DateField(verbose_name="Fecha") @staticmethod def encryptId(pedido_id): signer = Signer() return signer.sign(pedido_id) @staticmethod def decryptId(encrypted_id): try: signer = Signer() return int(signer.unsign(encrypted_id)) except BadSignature: return None class Meta: abstract = True class DetalleSalida(models.Model): ESPECIFICACION = ( ('REPOSICIÓN POR ROTO', 'REPOSICIÓN POR ROTO'), ('REPOSICIÓN POR DETERIORO', 'REPOSICIÓN POR DETERIORO') ) usuario= models.ForeignKey(pacienteArcoiris,on_delete=models.CASCADE,null=True, blank=True) producto = models.ForeignKey(ElementoArcoirisPersonal,on_delete=models.CASCADE,null=True, blank=True) cantidad= models.DecimalField(max_digits=10, decimal_places=2) especificacion= models.CharField(max_length=24, choices= ESPECIFICACION, verbose_name="Especificación") class Meta: abstract = True class SalidaDotacionPersonalFORM(SalidaDotaciónPersonal): id=models.AutoField(primary_key=True, verbose_name="ID",) usuario = models.ForeignKey(pacienteArcoiris,on_delete=models.CASCADE,null=True, blank=True) class Meta: verbose_name = "Salida Dotación Personal" verbose_name_plural = "Salidas Dotación Personal" def __str__(self): return str(self.usuario) class DetalleSalidaDotaciónPersonal(DetalleSalida): salida_dotacion_personal = models.ForeignKey(SalidaDotacionPersonalFORM,on_delete=models.CASCADE,null=True, blank=True) class Meta: verbose_name = "DETALLE SALIDA" verbose_name_plural = "DETALLE SALIDA" def __str__(self): return "DSDP" + str(self. salida_dotacion_personal)` #VIEWS.PY from django.shortcuts import render from django.contrib.auth.models import User from django.views.generic import TemplateView from report.utils import convert_to_64 from report.report import report from .models import DetalleSalidaDotaciónPersonal,SalidaDotacionPersonalFORM class Index(TemplateView): template_name = "index.html" … -
Migrating data from a JSONfield to individual fields
I have a DJango Model class in which it was decided to store a bunch of data in a blob form. The reasons for this decission are not clear to me ... Regardless I now have the task of converting that JSONField into individual Model fields. My question is, how would I go about creating a custom DJango migration that would extract the data from the JSONField and migrate it into the new fields? My first idea is to make a migration in which I add all the new fields, then a second migration that will be custom made. In this second one I will use the django orm to go through every instance of my model and extract the JSON data and then loop through the field structure and alter the newly added fields with the JSON values. The only issue that I could see is if the fields have special constrants then it would get pretty tedious to get everything wright. Any suggestions on my approach?