Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Embed OpenCV in Django Template
I'm trying to make simple local web app that will start the camera and have simple options like "Record" and "Save"(take a picture). I have read this post, and it does what it need. But the only problem is that i can't put it in a template or have the page and buttons show. So can someone give me some example on how to do it or hints what need to be done in order to have the camera show as frame in html? -
How to save a model in Django Rest Framework having one to one relationship
I have a Django model named BankDetail that has a one to one relationship with User. #BankeDetails class BankDetail(models.Model): account_holder_name = models.CharField(max_length=100) account_number = models.CharField(max_length=50, blank=True, null=True) iban = models.CharField("IBAN", max_length=34, blank=True, null=True) bank_name = models.CharField(max_length=100) bank_address = models.CharField(max_length=500) swift_bic_code = models.CharField(max_length=11) user = models.OneToOneField(MyUser,on_delete=models.CASCADE) accepting_fiat_currency = models.OneToOneField(AcceptedFiatCurrency) created_at = models.DateTimeField(auto_now_add=True,null=True) updated_at = models.DateTimeField(auto_now=True) The serializer is as listed below : class BankDetailSerializer(serializers.ModelSerializer): """Serializer for BankDetails""" class Meta: model = BankDetail fields = "__all__" def validate(self, data): if data['account_number'] or data['iban']: raise serializers.ValidationError("Please fill Account Number or IBAN") return data Request Payload : { "account_holder_name":"Aladin", "account_number":"1239893", "bank_name":"Aladin Bank", "bank_address":"Republic of Wadia", "swift_bic_code":"1", "user_id":"1", "accepting_fiat_currency_id":"1" } Now when I'm trying to save the model from my view, I get the following error : { "user": [ "This field is required." ], "accepting_fiat_currency": [ "This field is required." ] } How can I pass I refrence ob these objects, do I need to manually retrieve them from the db using the id's? -
Sharing session with threads in Django views
I'm trying to access a session variable with AJAX. I have different two views, the main one (index) and another one only returning the session value (refreshSession). The main one starts a thread that is changing the session value every second but when the view that only returns the session value access to it, the changes that the thread is doing are being lost. // views.py // def refreshSession(request): sesAlarm = request.session['alarm'] return JsonResponse({'alm': sesAlarm}) def index(request): request.session['alarm'] = 0 t = Thread(target = threadFunction, args=(request,)) t.daemon = True t.start() context={} return HttpResponse(template.render(context, request)) def threadFunction(request): while True: request.session['alarm'] += 1 time.sleep(1) // JS // var idAlarm = setInterval(function(){ $.ajax({ type:"POST", url:"/app/update_session/", cache: 'false', success: function(data) { alert(data.alm); } }); }, 5000); This code always shows alerts with '0'. I think the problem is that changes in the thread are not being reflected in the request in refreshSession() because request is not passed by "reference" to the thread (I'm a main C programmer). If I use a global variable instead of a session it works perfect, the alert shows the number increasing. But I've read that using global variables in views is not recommended. So, what am I missing? How … -
How to obtain Object Values from Class Based Views in Django
I'm using the DetailView to open a new page based on two variables of a model (dtcalculo and cdcarteira) where pk = 'dtcalculo' The purpose is to retrieve what dtcalculo and cdcarteira is used because I want to use this date to filter another two models. views.py class VisualizaFundoSolutions(DetailView): #slug_field = 'cdcarteira' context_object_name = 'fundo' template_name = 'prototipo_fundo.html' queryset = RmDadoscarteira.objetos.all() # Como o modelo tem duas primary keys, e necessario usar sobrescrever a funcao get_object def get_object(self): return RmDadoscarteira.objetos.get(pk=self.kwargs["pk"], cdcarteira=self.kwargs["cdcarteira"]) # A view trabalha com 3 templates utilizando o filtro de data e nome do fundo def get_context_data(self, **kwargs): # Obtendo nome do fundo e data context = super(VisualizaFundoSolutions, self).get_context_data(**kwargs) print(context) return context urls.py from portal_riscos.views import * from django.urls import path from django.contrib.auth.views import LoginView app_name = 'portal_riscos' # urlpatterns contém a lista de roteamento URLs urlpatterns = [ # Dashboard Solutions path('', FlagshipSolutions, name='dash_solutions'), path('solutions_fundos/<pk>/<cdcarteira>', VisualizaFundoSolutions.as_view(), name='solutions_fundos') ] Is there any way using get_context_data or get_object where can I store the "filter" variables? Thanks -
not returning token for user
I am creating user auth for my project with djangorestframework-jwt and I have created a superuser when i am going to try login with superuser's email and password i will have a token but when I try to register a new user it is registered but if i login to it it says { "non_field_errors": [ "Unable to log in with provided credentials." ] } even if i enter correct credentials first I have created a user registration it worked models.py class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') try: user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: raise def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password=password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self views.py jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class CreateUserAPIView(APIView): permission_classes = (AllowAny,) def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) … -
Starting docker with powershell dev script
I am doing a docker project from scratch, and following a tutorial (I am following the Django2 WebDevelopment Cookbook). I came upon a section, that I don't know how to convert to Powershell from Bash. I have the following script in my /bin/dev.ps1 #!/usr/bin/env bash # bin/dev # environment variables to be defined externally for security # - MYSQL_USER # - MYSQL_PASSWORD # - MYSQL_ROOT_PASSWORD DOMAIN=myproject.local DJANGO_USE_DEBUG=1 \ DJANGO_USE_DEBUG_TOOLBAR=1 \ SITE_HOST="$DOMAIN" \ MEDIA_HOST="media.$DOMAIN" \ STATIC_HOST="static.$DOMAIN" \ MYSQL_HOST="localhost" \ MYSQL_DATABASE="myproject_db" \ docker-compose $* I have edited the file to such, since the above wasn't working for Windows: #!/usr/bin/env bash # bin/dev # environment variables to be defined externally for security # - MYSQL_USER # - MYSQL_PASSWORD # - MYSQL_ROOT_PASSWORD $DOMAIN="myproject.local" $DJANGO_USE_DEBUG=1 $DJANGO_USE_DEBUG_TOOLBAR=1 $SITE_HOST="$DOMAIN" $MEDIA_HOST="media.$DOMAIN" $STATIC_HOST="static.$DOMAIN" $MYSQL_HOST="localhost" $MYSQL_DATABASE="myproject_db" docker-compose And now it gives me the standard output when you run docker-compose without any arguments. I am trying to also run the following from my terminal: MYSQL_USER=myproject_user \ > MYSQL_PASSWORD=pass1234 \ > ./bin/dev up -d Obviously this won't work in Windows, it even gives me an error that it can't find the MYSQL_USER command or anything. How do I edit the PS file so that I can use it for Windows? And how … -
How to map a Single User Model with multiple roles (student and teacher) to another model when relationship with the model varies based on user role?
So, I have a User model in Django which can have three roles - teacher, student or both. I have another Model, say Course which can have only one teacher but can have multiple students mapped to it. How do I relate these models with another? -
Django (or sqlite3) change(s) the sequence of attributes of a model
I'm using django with sqlite3, and here is my models.py: from django.db import models from django.conf import settings from django.utils import timezone class VoterDetails(models.Model): number = models.CharField(max_length=200,null=True) voter_id = models.CharField(null=True,max_length=200) elector_name = models.CharField(max_length=200,null=True) father_or_husband_name = models.CharField(max_length=200,null=True) has_husband = models.CharField(max_length=200,null=True) house_no = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) sex = models.CharField(max_length=6,null=True) ac_name = models.CharField(max_length=200,null=True) parl_constituency = models.CharField(max_length=200,null=True) part_no = models.CharField(max_length=200,null=True) year = models.CharField(max_length=200,null=True) state = models.CharField(max_length=200,null=True) filename = models.CharField(max_length=200,null=True) main_town = models.CharField(max_length=200,null=True) police_station = models.CharField(max_length=200,null=True) mandal = models.CharField(max_length=200,null=True) revenue_division = models.CharField(max_length=200,null=True) district = models.CharField(max_length=200,null=True) pin_code = models.CharField(max_length=200,null=True) polling_station_name = models.CharField(max_length=200,null=True) polling_station_address = models.CharField(max_length=200,null=True) net_electors_male = models.CharField(max_length=200,null=True) net_electors_female = models.CharField(max_length=200,null=True) net_electors_third_gender = models.CharField(max_length=200,null=True) net_electors_total = models.CharField(max_length=200,null=True) change = models.CharField(default="",max_length=200,null=True) def __str__(self): return self.elector_name As one can see, there is no attribute, which would claim to be the primary key. In this case, django generates an attribute id, which is an auto incrementing Auto field, which is chosen as the primary key. I did the migrations, and then checked the schema of the table temp_voterdetails thus generated.(temp is the name of my app.) sqlite> .schema temp_voterdetails CREATE TABLE IF NOT EXISTS "temp_voterdetails" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "age" varchar(200) NULL, "ac_name" varchar(200) NULL, "change" varchar(200) NULL, "district" varchar(200) NULL, "elector_name" varchar(200) NULL, … -
Specify related string field in Django Rest Framework
Django 1.11, Django Rest Framework 3.6. I have 2 models, Foo and Bar: class Foo(models.Model): name=models.CharField() sex=models.CharField() class Bar(models.Model): type=models.CharField() foo=models.ForeignKey(Foo) In my serializers.py I have: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ('sex',) class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(many=False) class Meta: model = Bar fields = ('type', 'foo',) This produces JSON like this: { "type": "abcdefg", "foo": { "sex": "male" } } What I really want is for the "foo" field to be flat, i.e.: { "type": "abcdefg", "foo": "male" } One possible solution would be to use the StringRelatedField, but this would entail setting the __str__ method of the Foo model to return the sex field, which I do not want. -
Django: Avoid duplicated
The following for loop is shown to me as 3x duplicate. Do you have any idea how to avoid that? @cached_property def social_ticketing_coin_allocation_formset(self): initial = [] for ticket in self.tickets_as_list: coin_allocation = Coins.objects.filter(ticket=ticket['ticket']) if not coin_allocation.exists(): initial.append({'ticket': ticket['ticket']}) extra = len(initial) -
How give custom permission in middleware - Django
I am creating Custom Access Control List. For that i have created a model class AclRoleAccess(models.Model): acl_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE) acl_company = models.ForeignKey(Company, on_delete=models.CASCADE) acl_functionality = models.ForeignKey(AclFunctionality, on_delete=models.CASCADE) acl_has_access = models.BooleanField() class Meta: db_table = "acl_role_accesses" Can i use has_perm for this model. How can i restrict user can any give me suggesstion. What is actual codename in permission table -
post an array of data to database
I have this model: name = models.CharField(max_length=50, unique=True) readable_name = models.CharField(max_length=50, unique=True) permissions = models.ManyToManyField(Permission, related_name='permissions_group', db_table='role_permissions', blank=False,null=False) and this serializer: class Meta: model = models.Role fields = '__all__' and I have this post class: serializer = serializers.RolePostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": _("Added Successfully")}, status=status.HTTP_201_CREATED) Front end give me this kind of data: "name": "test role", "permissions": { "0": 5, "1": 2, "2": 6, "3": 7 }, "readable_name": "test" } I dont know how I can give my permission an array of data like this. In my postman I can give just one permission id and its ok but I cannot give more than one -
Formset is not filtering
Anyone who understands, why my queryset is not working? The filter doesn't apply and it's showing all: CoinAllocationFormset = modelformset_factory( Coins, fields=('ticket', 'coins'), # form=SocialTicketingCoinAllocationForm, extra=0, ) return CoinAllocationFormset( data=self.request.POST or None, initial=initial, queryset=Coins.objects.filter(ticket__event=self.request.event), ) -
Django tables2 sorting
I have a django model that I am rendering with django tables2. I am trying to make the columns sortable. It appears by default clicking on the headers should sort them already looking at the browser address localhost:10000/gui/?sort=max_val But it doesn't do anything. I added a method following https://django-tables2.readthedocs.io/en/latest/pages/ordering.html But this still does not order anything. class Strategy(models.Model): ... max_val = models.DecimalField(max_digits=32, decimal_places=0) class DfTable(tables.Table): max_val = tables.Column() def order_max_val(self, QuerySet, is_descending): QuerySet = QuerySet.order_by(('-' if is_descending else '') + 'max_val') return (QuerySet, True) Any idea what I am missing here? -
What should be the data type to store Currency Symbol in Django Models
I have a Django model that relates to the currency with fields like currency name, currency code and currency symbol. class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_code = models.CharField(max_length=3) currency_symbol = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True,null=True) updated_at = models.DateTimeField(auto_now=True) The currency_symbol field will hold a symbol for a particular currency, for example "€". However when I'm trying to save the model, I'm getting the following exception, django.db.utils.DataError: (1406, "Data too long for column 'currency_symbol' at row 1") So what should be the correct datatype? -
Django rest API deploy on apache
I have created a django application and deployed it on the server.I have run the application through python manage.py runserver 8000 & and handle the requests on the apache server through proxy ProxyPass "/" "http://www.example.com/" ProxyPassReverse "/" "http://www.example.com/". But there is a issue that I am facing while testing the api through JMeter, when i am running a test case for 10 users my python service over the server gets killed automatically. What i am doing wrong or what i have to do more to resolve the above test scenario,please suggest? -
Datatables with Django can not fetch data from MySQL Database
I am trying to fetch data by searching in the default search bar provides by the datatables using Django. The default view shows up but when I search in the search box, It shows nothing. The view it shows like this: My View is this: def searchProductTable(request): xh = ProductLaptop.objects.all() context = { "xh": xh } return render(request, "searchTableView.html", context) for the model below: class ProductLaptop(models.Model): laptops_name = models.CharField(max_length=500, null=True, blank=True) laptops_url = models.CharField(max_length=500, null=True, blank=True) laptops_price = models.IntegerField(null=True, blank=True) laptops_image = models.CharField(max_length=400, null=True, blank=True) brand_name = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return self.laptops_name I know the model is not correct and at the same time I do not know how will I implement the model cause I do not have that much experience with Django. The code of my .html file is: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Search Table</title> <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> </head> <body> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Seller</th> <th>Price</th> </tr> </thead> <tbody> {% for foo in xh %} <tr> <td>{{ foo.laptops_name}}</td> <td>{{ foo.brand_name}}</td> <td>{{ foo.laptops_price}}</td> {% endfor %} </tr> </tbody> </table> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> … -
Unable to collectstatic
I tried to run python manage.py collectstatic, but recieved the following error. I'm not sure where to even begin troubleshooting. There doesn't seem to be much helpful information within the error information below. Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 189, in handle collected = self.collect() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 104, in collect for finder in get_finders(): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\finders.py", line 277, in get_finders yield get_finder(finder_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\staticfiles\finders.py", line 286, in get_finder Finder = import_string(import_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 15, in import_string raise ImportError("%s doesn't look like a module path" % dotted_path) from err ImportError: d doesn't look like a module path Any ideas would be appreciated! Thanks! -
Bower not installed
I'm attempting to install django-scheduler, which requires bower. I've followed the Installation instructions here. https://github.com/llazzaro/django-scheduler I ran pip freeze and can see that I have django-bower==5.2.0 installed. Last step within the github instructions is as follows: install bower dependencies with: ./manage.py bower install I went into my project directory and ran the following command: manage.py bower install I get the following error: BowerNotInstalled: Bower not installed, read instruction here - http://bower.io/ I've gone to the site and can't see anything about the python install. Any help would be appreciated. Thanks! -
Static method returning empty list in Django
I am trying to run a Django app on local server. It works fine on mu Ubuntu machine but in mac, I can't get the CSS for localhost:8000/admin and localhost:8000/docs to load. On digging further, I found out that the static URL in main "urls.py" file return an empty list instead of a URL pattern. Does anyone have an idea why it is like that on the new mac system? -
password reset implementation with djoser
I wanted to use djoser for the reset password functionality and as per the documentation " PASSWORD_RESET_CONFIRM_URL URL to your frontend password reset page. It should contain {uid} and {token} placeholders, e.g. #/password-reset/{uid}/{token}. You should pass uid and token to reset password confirmation endpoint. I have done the following: PASSWORD_RESET_CONFIRM_URL': 'reset/password/reset/confirm/{uid}/{token}', url url(r'^reset/password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', PasswordResetView.as_view(),), View : class PasswordResetView(APIView): def get (self, request, uid, token): post_data = {'uid': uid, 'token': token} return Response(post_data) In my mail I get this link : http://127.0.0.1:8000/reset/password/reset/confirm/Mjk/538-954dccbc1b06171eff4d This is obvious that I will get : { "uid": "Mjk", "token": "538-954dccbc1b06171eff4d" } as my output but I wanted to go to auth/password/reset/confirm when the user clicks the link in the mail. -
Get title from object closest to date, django model
I have to models: Week: class Week(models.Model): week_id = models.Charfield(unique=True, null=False, primary_key=True) year = models.PositiveSmallInteger() weeknumber = models.PositiveSmallInteger() ... and Deadline class Deadline(models.Model): deadline_type = models.CharField() end_at = models.DateTimeField(blank=False) week_id = models.ForeignKey(Week, related_name='deadlines', on_delete=models.CASCADE) ... Which gives me an output like: { "weeknumber": 1, "leaflet_year": 2019, "week_id": "01_2019", "deadlines": [ { "deadline_type": "Some Deadline type", "end_at": "2019-10-23T14:00:00Z", }, ... ] } What I want to achieve, is to annotate the Week object with the deadline_typeof the deadline object which have the end_atclosest to today. I can annotate the end date, but I simply have no idea on how to get the type. -
Analysing and improving the performance of a query generated by Django's ORM (SORT)
I have a not-so-complex (imho) filtering logic based on several conditions in my Django models. There is one particular query which takes an inusual amount of time to finish. The query is built based on those two querysets: queryset = self.serializer_class.Meta.model.valid_pricelist_objects.filter( Q(drug_prices__pricelist__price_destination__to_all_insurances=True ) | # pylint: disable=line-too-long Q( drug_prices__pricelist__price_destination__to_organization_data__organization__uuid =self.kwargs.get('i_uuid'))) return queryset and return super().get_queryset().filter( Q(active=True), Q(drug_prices__pricelist__active=True), # Lista de precios activa # Q(drug_pictures__is_main=True), # Que tenga una imagen # TODO: Hacer filtros por pais PriceListCountries Q( Q(drug_prices__pricelist__expires=False) | # Que tenga precios que no caducan o Q( Q(drug_prices__pricelist__expires=True), # Que tenga precios que si caducan Y Q(drug_prices__pricelist__datestart__date__lte=timezone.now()), # Fecha de inicio menor que hoy Y Q(drug_prices__pricelist__dateend__date__gte=timezone.now()) # Fecha final mayor que hoy ) ) ).distinct().prefetch_related( 'categories__contexts', 'brands', 'drug_prices__pricelist', 'drug_pictures', 'drug_prices__pricelist__price_destination', ) The second querysets wraps the first one (via the super() call). The resulting query looks like this: SELECT DISTINCT "phdrug_phdrug"."id", "phdrug_phdrug"."uuid", "phdrug_phdrug"."default_description", "phdrug_phdrug"."ean", "phdrug_phdrug"."parent_ean", "phdrug_phdrug"."reg_num", "phdrug_phdrug"."atc_iv", "phdrug_phdrug"."product_type", "phdrug_phdrug"."fraction", "phdrug_phdrug"."active", "phdrug_phdrug"."loyal", "phdrug_phdrug"."patent", "phdrug_phdrug"."chronics", "phdrug_phdrug"."recipe", "phdrug_phdrug"."deal", "phdrug_phdrug"."specialized", "phdrug_phdrug"."armored", "phdrug_phdrug"."hight_speciality", "phdrug_phdrug"."temp_8_15", "phdrug_phdrug"."temp_15_25", "phdrug_phdrug"."temp_2_8", "phdrug_phdrug"."temp_less_15", "phdrug_phdrug"."new", "phdrug_phdrug"."mdk_internal_code", "phdrug_phdrug"."mdk_single_id", "phdrug_phdrug"."is_from_mdk_db", "phdrug_phdrug"."top", "phdrug_phdrug"."laboratory_id", "phdrug_phdrug"."specialty_id" FROM "phdrug_phdrug" INNER JOIN "monetary_drugprice" ON ( "phdrug_phdrug"."id" = "monetary_drugprice"."drug_id" ) INNER JOIN "monetary_pricelist" ON ( "monetary_drugprice"."pricelist_id" = "monetary_pricelist"."id" ) INNER JOIN "monetary_drugprice" T4 ON ( "phdrug_phdrug"."id" = T4."drug_id" ) … -
Django- update() and get_or_create() check entry count before uploading
Is there any way to check how many objects would be updated or created before committing to the DB? Something like this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" onclick="return confirm('Upload File? {{created_objects}} Objects will be created. {{updated_objects}} Objects will be updated')">Upload</button> </form> And then in the view with open(str(csv_file)) as file: number_of_lines = len(file.readlines()) reader = csv.reader(file) for row in reader: id += 1 try: _, p = CSV3.objects.get_or_create(id = id, defaults = {'gebaeudebereich' : row[0], 'gebaeudenummer' : row[1], 'ebene' : row[2], 'raum' : row[3], 'dose' : row[4], 'switch_ip' : row[5], 'switch_port' : row[6], 'datum' : row[7], 'akteur' : row[8]}) created_objects += 1 except IntegrityError: _, p = CSV3.objects.filter(id = id).update(gebaeudebereich=row[0], gebaeudenummer=row[1], ebene=row[2], raum=row[3], dose=row[4], switch_ip=row[5], switch_port = row[6], datum = row[7], akteur = row[8]) updated_objects += 1 #messages.INFO("Objects Created: %(created_objects)s") #messages.INFO("Objects Updated: %(updated_objects)s") return redirect('appp:index') form = UploadFileForm() return render( request, "appp/file_upload.html", {"form": form} ) Thanks in advance -
How to iterate over a json object in Python?
I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go? { "results": { "ALL": { "currencyName": "Albanian Lek", "currencySymbol": "Lek", "id": "ALL" }, "KWD": { "currencyName": "Kuwaiti Dinar", "id": "KWD" }, "LSL": { "currencyName": "Lesotho Loti", "id": "LSL" }, "MYR": { "currencyName": "Malaysian Ringgit", "currencySymbol": "RM", "id": "MYR" }, "MUR": { "currencyName": "Mauritian Rupee", "currencySymbol": "₨", "id": "MUR" } } } I tried this : for key,value in currencies.results : #print(currency) #print(value) However, I get the following error : "Too many attribures to unpack, expected 2 Can someone help me with this?