Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-framework PUT and DELETE generic view
So I have this model over here. class Member(BaseModel): objects = models.Manager() user = models.ForeignKey('api_backend.User', db_index=True, on_delete=models.CASCADE) roles = models.ManyToManyField('api_backend.Role') cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE) Serializer for the same class PartialMemberSerializer(serializers.ModelSerializer): class Meta: model = Member exclude = ['cluster', 'roles'] @classmethod def get_user(cls, obj): return PartialUserSerializer(obj.user).data user = serializers.SerializerMethodField() I want to have a generic view where: the member object of the authenticated user who is present in a particular cluster can be either deleted or put. I have my base destroy view here class MemberPutDeleteView(generics.DestroyAPIView): queryset = api_models.Member.objects.all() serializer_class = api_serializers.PartialMemberSerializer permission_classes = [permissions.IsAuthenticated] def get_object(self): return api_models.Member.objects.get( user=self.request.user, cluster__id=self.kwargs['pk']) def destroy(self, request, *args, **kwargs): member = self.get_object() # if the member is the owner, don't remove member # the cluster must be deleted by the cluster-deletion endpoint. if member.cluster.owner == member.user: raise exceptions.ValidationError("you cannot leave this cluster as you own it.") return super(MemberPutDeleteView, self).destroy(request, *args, **kwargs) How can I also add a put method to this view? What I want to do here is: get the cluster id from the pk url parameter filter the member object which has the cluster id and also the user object as the requested user finally delete the object on delete request if … -
save result of get_absolute_url in django model Field
I want to save result of post.get_absolute_url() in my django model as Field. def get_absolute_url(self): return reverse('post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) For example absolute_url = models.CharField(...'result of post.get_absolute_url()'...). Is there any way to do this? Thanks. -
How to use get_or_create? Error: get() returned more than one Patient -- it returned 7
I have a function for fetch API where I create a Django model object for each object in the JSON and store the data in django model. The problem here is everytime I call the route it creates the records again and again, because I use create method, but I made an research that the best way to stop that is to use get_or_create. So, I tried this method but it looks like I missed something, because I got an error: feedback.models.Patient.MultipleObjectsReturned: get() returned more than one Patient -- it returned 7! this is my code before I have 2 for loops so I can loop through every patient and then through every role and save patient with a role: # FetchApi for Patients def fetchapi_patients(request): url = 'http://localhost:8000/core/users/roles/patient' headers={"Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imhha2FuQGdvLmNvbSIsImV4cCI6MTYxMDAxMTM0MSwib3JpZ19pYXQiOjE2MTAwMDc3NDF9.k2204d094DNUbEfFt8M_7chukOSjWWwfesPOH5jIiP8"} response = requests.get(url, headers=headers) #Read the JSON patients = response.json() #Create a Django model object for each object in the JSON and store the data in django model (in database) for patient in patients: Patient.objects.create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID']) for role in patient['Roles']: Role.objects.create(role_name=role['name']) return JsonResponse({'patients': patients}) this is when I tried to use get_or_create method: for patient in patients: patientDatabase, created = Patient.objects.get_or_create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID']) for role in … -
How to save Image using CharField max_length=1024 i.e longext in django
I am working on a project where we want the profile pic of user to be in a CharField i.e longtext. Now, in ModelForm for updating the user's profile I want to get profile pic and want to resize and compress it and save it in database with unique name like using timestamp. The problem that I have is that I can get image name using cleaned_data from form but cannot process it for resize or compression and it gives me the error of no file or directory is found -
Filtering object with multiple related models with M2M and ForeignKey
I want to filter university programs in list view. I have near to 200000 objects. When I do the query in ProgramSearchView I get double the number of objects because of "subject__parent__title". I am very bad at queries. How can I write the most efficient query here and which query do you think suites the most? Note: I've shortened fields in some models in order to decrease complexity here. My Model: class Program(models.Model): slug = models.SlugField(null=False, blank=False, unique=True, max_length=255) program_id = models.IntegerField(_("ID")) title = models.CharField(max_length=199) date_added = models.CharField(max_length=99, blank=True, null=True) requirements = JSONField(blank=True, null=True) details = JSONField(blank=True, null=True) academic_award = models.ManyToManyField("program.AcademicAward", verbose_name=_("Academic award")) subject = models.ManyToManyField("program.Subject", verbose_name=_("Subject"), blank=True) school = models.ManyToManyField("program.School", related_name='school', blank=True) class AcademicAward(models.Model): title = models.CharField(_("title"), max_length=250) # for ex. M.Sc., B.Sc. description = models.CharField(_("about"), max_length=450, null=True, blank=True) category = models.CharField(_("Category"), max_length=150, blank=True, null=True) # for ex. Degree, Certificate or Diploma class School(models.Model): title = models.CharField(_("Title"), max_length=950) description = models.CharField(_("About"), max_length=950, blank=True, null=True) campus = models.ForeignKey("program.Campus", verbose_name=_("Campus"), on_delete=models.CASCADE, max_length=255) class Campus(models.Model): title = models.CharField(_("title"), max_length=150) description = models.CharField(_("About"), max_length=950, null=True, blank=True) city = models.CharField(_("city"), max_length=150, null=True, blank=True) country = models.CharField(_("country"), max_length=150, null=True, blank=True) university = models.ForeignKey("program.University", verbose_name=_("university"), on_delete=models.CASCADE, max_length=255) class University(models.Model): title = models.CharField(_("Title"), max_length=250, null=True, blank=True) description … -
python api image uploading issue with request data
My api to save request data with image is like: class AddImageApiView(APIView): @swagger_auto_schema( operation_id="Add Image", operation_summary="Add Image", operation_decription="Add Image", ) @validator() def post(self, request, userdetail=None, version=None, format=None): data = request.data tasks = [] if data.getlist('files'): try: for file in data.getlist('files'): task_res = TaskResources(file=file, file_type='1', task=121) task_res.save() except Exception as e: print(e) and i am hitting the api like : url = settings.BASE_URL+'api/users/childs/addtask/' headers = {'token':settings.HTTP_TOKEN,'source':'WEB'} files = [] files.append(list(request.FILES.getlist('files'))) params = { 'files' : files } addtasksCall= requests.post(url, data=params,headers=headers) When i am hiiting the api image name only saving in my db . image is not getting uploaded on folder also not full path save in db . why it is saving only image name even i am sending the image object can anyone please help me related this ?? -
How to apply exclude for first resultant item of select_related() query in django
I am doing a left join using select_related() and then excluding few things based on condition using below code class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate__lt = timezone.now(),pmdclinicalruleid__retireddate__gt = timezone.now()).exclude(Q(rulename__isnull=True) | Q(rulename__exact='') | Q(rulename__startswith='OptumFormulary')) The above code applies exclude for entire select_related results. Instead i need to apply exclude only for first result item from select_related(). Any way to implement this? -
Making run a django web app inside docker along side a web app outside docker
As the title say, i'm trying to deploy a toy web app (Django) powered by Docker, with 3 containers, one for the app, one for postgresql and the last one for nginx. I want to deploy it on a virtual instance where i've already a running web app (Django) outside of Docker, with Nginx install globally on the machine. I've managed to making run both app. The first one, outside of docker, is accessible by a subdomain name (firstapp.mydomain.com) and as a Let's Encrypt Certificate. The second one is accessible by ip with 1337 port. I now want to access my second app (the docker one), through a second subdomain, that i've created (myapp2.mydomain.com), but i think there is some conflict with Nginx installed globally, becouse when i want to reach secondapp.mydomain.com, i'm always redirected to firstapp.mydomain.com Here is my nginx configuration : The first app (nginx install globally on the machin) file configuration upstream firstapp_server { server 127.0.0.1:8000; } server { listen 80; server_name firstapp.mydomain.com; return 301 https://firstapp.mydomain.$request_uri; } server { listen 443 ssl; server_name firstapp.mydomain.com; root /path/to/my/app; ssl_certificate /etc/letsencrypt/live/firstapp.mydomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/firstapp.mydomain.com/privkey.pem; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) … -
I have a single defined primary key in my model, but Django throws multiple primary keys error
This is my code class BsValuesTTM(models.Model): corpname = models.CharField(max_length=100) co_name = models.CharField(max_length=100, primary_key=True) ACR = models.FloatField() Inventory = models.FloatField(null=True) CashCE = models.FloatField(null=True) CurrentAssets = models.FloatField() GrossPPE = models.FloatField() AccDepn = models.FloatField(null=True) NetPPE = models.FloatField() Intangibles = models.FloatField(null=True) NCA = models.FloatField() Assets = models.FloatField() i only have a single primary key in my model, Django throws this error django.db.utils.ProgrammingError: multiple primary keys for table "Main_bsvaluesttm" are not allowed I have changed the field for primary key, earlier it was corpname, and that field used to be a foreign key. I am using Postgresql12 with Django. -
Django Caching View Per User
I'd like to cache a view in my Django app. However, the result of the view varies for every user. I've tried using vary_on_cookie, but I can't get it to work: @cache_page(60 * 15) @vary_on_cookie def my_view(request): ... Is there a better way to do this? Thanks in advance. -
Encoding error occurs when importing csv file from Heroku
I made a project with a django. There was no problem when importing csv files in local. But when I put it on Heroku and import data from Heroku admin, this error occurs. "Imported file has a wrong encoding: 'utf-8' codec can't decode byte 0xba in position 99: invalid start byte" How do I solve this? -
I Can't Solve NoReverseMatch at /events/ Error
I got this error when I add event with status false. There is no problem at status true: NoReverseMatch at /events/ Reverse for 'event-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['events/(?P<url_sistem>[^/]+)/$'] I couldn't see the cause of the error It's my views.py file: from django.shortcuts import render, get_object_or_404 from .models import Event def event_list(request): events_f = Event.objects.filter(status=False) events_t = Event.objects.filter(status=True) return render(request, 'etkinlik/event_list.html', {'events_f':events_f , 'events_t':events_t}) def event_detail(request, url_sistem): event = get_object_or_404(Event, url_sistem=url_sistem) return render(request, 'etkinlik/event_detail.html',{'event':event}) This is urls.py: urlpatterns = [ path('', views.event_list, name='event_list'), path('<str:url_sistem>/', views.event_detail, name='event-detail') ] And this template file: {% extends 'base.html' %} {%block title%}Events | {%endblock%} {% block content %} <div class="container mt-4"> <div class="jumbotron"> <h4 class="display-4">Öne Çıkarılan Etkinlik</h4> <p class="lead mb-5">Bu etkinlik şuandaki en önemli ve popüler etkinliktir. Katılabilen herkesin katılmasını isteriz</p> {% if not events_t %} <h2>Şu anda öne çıkarılan yok</h2> {% else %} {% for event_t in events_t %} <a href="{% url 'event-detail' event_t.url_sistem %}" style="color:black;"> <div class="card mb-3" style="max-width:700px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/{{ event_t.img_event }}" class="card-img" alt="etkinlik_foto"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{event_t.title}}</h5> <p class="card-text">{{event_t.exp}}</p> <p class="card-text"><small class="text-muted">Etkinlik Tarihi: {{event_t.event_date}}</small></p> </div> </div> </div> </div> </a> {% endfor %} {% endif %} </div> {% for event_f … -
django.db.utils.OperationalError: could not connect to server: Connection timed out
Im trying to connect my project on heroku to a AWS RDS, I have checked everything, read many articles on stackoverflow and google to no avail. Please help... It keeps saying : django.db.utils.OperationalError: could not connect to server: Connection timed out I dont know why. I have created an IAM on AWS, I dont know if i need to connect that to the database somehow, and actually it was correctly correctly when it was connect to heroku default database. Please help. What do i need to provide to facilitate this? -
Error when trying to assign a group to a user
I am trying to assign a group to a user but without the need to use the django manager, but I run into a problem and it tells me that "<User: island>" must have a value for the field "id" before this many-to-many relationship can be used. This is my view: class UserCreationView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView): permission_required = 'users.add_user' login_url = 'users:login' template_name = 'users/register.html' model = User form_class = UserForm success_message = 'El usuario fue creado exitosamente' success_url = reverse_lazy('users:user') def form_valid(self, form): self.object = form.save(commit=False) group = Group.objects.get(pk=self.request.POST.get('groups')) self.object.groups.add(group) self.object.save() -
Generating sub domain on registration [Django app]
I am creating a Django chat app in which after an admin registration I want to create a sub domain of newly registered name. Example- my domain is www.localhost.com::8000 after user with name XYZ registered a sub domain must be created as www.XYZ.localhost.com. Now admin can invite its employees to register on this subdomain to join this subdomain specific chat channels. -
Web Push Django in Safari
I am using push notifications in Django, I am using the library https://github.com/safwanrahman/django-webpush It work correctly in Chrome and Firefox, but in Safari I have a JS error. TypeError: undefined is not an object (evaluating 'reg.pushManager.getSuscription') -suscribe -Anonymus Function The code is this: function subscribe(reg) { // Get the Subscription or register one reg.pushManager.getSubscription().then( function(subscription) { var metaObj, applicationServerKey, options; // Check if Subscription is available if (subscription) { return subscription; } metaObj = document.querySelector('meta[name="django-webpush-vapid-key"]'); applicationServerKey = metaObj.content; options = { userVisibleOnly: true }; if (applicationServerKey){ options.applicationServerKey = urlB64ToUint8Array(applicationServerKey) } // If not, register one reg.pushManager.subscribe(options) .then( function(subscription) { postSubscribeObj('subscribe', subscription, function(response) { // Check the information is saved successfully into server if (response.status === 201) { // Show unsubscribe button instead subBtn.textContent = 'Eliminar suscripción'; subBtn.disabled = false; isPushEnabled = true; showMessage('La suscripción se ha eliminado correctamente'); } }); }) .catch( function() { console.log('Subscription error.', arguments) }) }); } -
Django form data with azure logic apps
I got a django form data which I need to post to azure logic app. When I post the data I get this error: {"error":{"code":"NoResponse","message":"The server did not receive a response from an upstream server. Request tracking id '08585915990752009043423379830CU49'."}} When I check azure logs I see this error: BadRequest. The property 'content' must be of type JSON in the 'ParseJson' action inputs, but was of type 'application/x-www-form-urlencoded'. So as I understand I need to change this data to json as its sent as application/x-www-form-urlencoded. So My question is how can I do that? I'm new to django so any help would be great. My code looks like this: Views.py def home(request): context = initialize_context(request) if request.method == 'POST': vardas = request.POST.get('vardas') ToDate = request.POST.get('ToDate') FromDate = request.POST.get('FromDate') Pastabos = request.POST.get('Pastabos') username = request.POST.get('username') Login_form.objects.create(vardas=vardas,ToDate=ToDate,FromDate=FromDate,Pastabos=Pastabos,username=username) return render(request, 'loginas/home.html', context) My form in home.html {% extends "loginas/layout.html" %} {% load static %} {% block content %} <div class="container"> <h1 class="d-flex justify-content-center">Login Testas</h1> <p class="d-flex justify-content-center">Dominari Prisijungimas</p> {% if user.is_authenticated %} <form action="http://link_to_azure" method="POST"> {% csrf_token %} <div class="form-group"> <label>Vartotojas</label> <input class="form-control" name="vardas" type="text" value="{{user.name}}"readonly> </div> <div class="form-group"> <input class="form-control" name="username" type="text" value="{{user.email}}"hidden> </div> <div class="form-row"> <div class="col"> <div class="form-group"> <label>Nuo</label> <input class="form-control" … -
Nested subquery distinction to annotate sum
So I'd like to annotate a sum to a queryset, which has a little calculation rule with vars from remote tables. facturen = Factuur.objects.values('inkoopopdracht').filter( inkoopopdracht=OuterRef('pk'),) gefactureerd = facturen.annotate( gefactureerd=Sum(Case( When( factuurpost__inkooppost__btw__systematiek=2, then=(F( 'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs'))), default=F( 'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs')*( 1+F('factuurpost__inkooppost__btw__percentage')), output_field=DecimalField(), )), ).values('gefactureerd') qs = qs.annotate( factuursom=Subquery(gefactureerd.values( 'gefactureerd'), output_field=DecimalField()), ) The result of the above query is satisfactory. Except when there is a multiple of 'factuurpost'. In this case the sum seems to be multiplied with factuurpost instances. A fix for this, would be 'distinct=True' on the Sum. However since it only distincts values and not instances, this introduces a new problem. Similar values are no ignored, yielding the wrong sum. This seems to be an issues other people have come across with as well, e.g. : Django Count and Sum annotations interfere with each other Now, I used the solution there, with the subquery. I tried to nest the subquery to no avail. Does anyone see a potential solution to have it calculate the right sum in all cases? -
django - apscheduler how to keep job when uwsgi restart
django - 2.2.12 apscheduler - 3.6.3 I would like to set the notification to be sent two weeks after the user executes a specific task. scheduler.py import logging import time from apscheduler.schedulers.background import BackgroundScheduler logger = logging.getLogger(__name__) class JobLauncher: _sched = None def __init__(self): JobLauncher._sched = BackgroundScheduler() JobLauncher._sched.start() def __str__(self): return "JobLauncher" def run(self, job): return self.run_job(job) def stop(self, job): JobLauncher._sched.remove_job(job.name) def shutdown(self): if JobLauncher._sched.running(): logger.debug('Scheduler is shutting down.') JobLauncher._sched.shutdown() else: logger.warn("Cannot shutdown scheduler because scheduler is not running at the moment. please check scheduler status.") def run_job(self, job): if JobLauncher._sched.get_job(job.name) is None: _job = JobLauncher._sched.add_job(func=job.runMethod, trigger='date', id=job.name, args=job.job_params,run_date = job.job_date) return True return False class CommonJob: def __str__(self): return "Job Infos : {name : %s, job_params : %s}" % (self.name, self.job_params) @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name @property def job_date(self): return self._job_date @job_date.setter def job_date(self, new_job_date): self._job_date = new_job_date @property def job_params(self): return self._job_params @job_params.setter def job_params(self, new_job_params): self._job_params = new_job_params @property def runMethod(self): return self._runMethod @runMethod.setter def runMethod(self, new_runMethod): self._runMethod = new_runMethod class JobLauncherHolder: _launcher = None @staticmethod def getInstance(): if not JobLauncherHolder._launcher: JobLauncherHolder._launcher = JobLauncher() return JobLauncherHolder._launcher Add Job Code from utils.scheduler import JobLauncherHolder,CommonJob def event(self,userUID): launcher = JobLauncherHolder.getInstance() if launcher: … -
Django File Download Issue(filename issue & multiple files issue)
I am designing a django application which converts csv files to pipe delimited and download converted files. from more_itertools import chunked def submit(request): #form requests and file uploads #conversion function, this function converts csv files and chunks them into the 10000 rows and creates new files for every 10000 lines. def file_conversion(input_file,output_file_pattern,chunk_size): with open(input_file,"r+") as fin: # ignore headers of input files for i in range(1): fin.__next__() reader = csv.reader(fin, delimiter=',') for i, chunk in enumerate(chunked(reader, chunk_size)): with open(output_file_pattern.format(i), 'w', newline='') as fout: writer = csv.writer(fout,reader,delimiter='^') writer.writerow(fed_headers) writer.writerows(chunk) script_dir = os.path.dirname(os.path.abspath(__file__)) dest_dir = os.path.join(script_dir, 'temp') try: os.makedirs(dest_dir) except OSError: pass path =os.path.join(dest_dir,code+'{:01}.csv' ) #code is received from form # the function creates converted files such as code1.csv, code2.csv, code3.csv,etc file_conversion(i/p file from upload,path,10000) base_name = os.path.basename(path) #returns just a file name # all requirements are passed into context # 'submit.html' is also returned. def download(request): path = request.GET.get('path') base_name1 = os.path.basename(path) context = {'path': path, 'base_name1': base_name1} with open(path, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name1 return response The application creates files as code1.csv, code2.csv, code3.csv, etc. But in the params path and base_name, it looks to download code{01}.csv. How to properly arrange this filename format and … -
Django : ImportError
I have an app called users_auth and in the models.py file I have two Models. PENDING = 1 APPROVED = 2 REJECTED = 3 APPROVE_USER_STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'REJECTED'), ) class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_police = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) user_status = models.IntegerField(choices=APPROVE_USER_STATUS, default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, null=True, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_info') full_name = models.CharField(max_length=100, null=True, blank=True) cell = models.CharField(max_length=11, null=True, blank=True) address = models.CharField(max_length=200) profile_picture = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=True) updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='update_profile', null=True, blank=True) description = RichTextUploadingField(null=True, blank=True) def __str__(self): return "{username}'s Info".format(username=self.user) This code is Working Fine. But I want to add two more fields in UserProfile Model. expertise = models.ManyToManyField(Expertise) hospital = models.ForeignKey(Hospital, on_delete=models.SET_NULL, related_name='hospital', null=True, blank=True) After adding these two lines, If I run makemigrations command it shows: ImportError: cannot import name 'APPROVE_USER_STATUS' from 'users_auth.models' I have imported User & APPROVE_USER_STATUS from users_auth App in other app's model file by: from users_auth.models import APPROVE_USER_STATUS, User N.B : Import was working fine before adding these two fields. What could be the reason? -
How to make nested datatable using Django and Jquery
I have a master table and multi details tables. I want to display it using django-datatable. How to modify it to chow details as collapsible table inside master table row? -
Django Filter latest files
I have a model like, class Type(CommonBase): """ Allowed document types """ DOCUMENT_CLASS_CHOICES = ( ('C', 'Credit Card'), ('D', 'Debit Card'), ('SD', 'Supporting Documents'), ) MODEL_TYPE_CHOICE = ( ('person', 'Person'), ('bank', 'Bank'), ('all', 'All') ) document_title = models.CharField(max_length=100) document_class = models.CharField(choices=DOCUMENT_CLASS_CHOICES, max_length=3, default='C') model_type = models.CharField(choices=MODEL_TYPE_CHOICE, max_length=50, default='person') class Document(CommonBase): doc_type = models.ForeignKey(Type, on_delete=models.PROTECT) uploaded_datetime = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(Person, on_delete=models.CASCADE) comment = models.CharField(max_length=200, null=True, blank=True) I can upload Multiple credit card or multiple debit card details against the same user. So if a user has uploaded 2 credit card documents and 3 debit card documents, how the djnago query is supposed to be for getting latest uploaded credit card and debit card document details. -
how to add current active user as foreign key to the create post model in djangorestframework?
how to add current active user as foreign key to the create post model in djangorestframework ? models: class DoctorProfile(models.Model): id=models.AutoField(primary_key=True) name = models.CharField(_('name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) otp = models.IntegerField(null=True, blank=True) class Doctor_clinic(models.Model): clinic_id = models.AutoField(primary_key=True) doc_profile = models.ForeignKey(DoctorProfile,related,on_delete=models.CASCADE) clinic_name = models.CharField(max_length=150) clinic_address = models.CharField(max_length=150) City = models.CharField(max_length=50) state = models.CharField(max_length=50) pincode = models.IntegerField() #how to get the forign key in serializers I wrote in this way, is this correct/relevent? class UserSerializer(serializers.ModelSerializer): # mobile = serializers.RegexField("[0-9]{10}",min_length=10,max_length=10) password = serializers.CharField(write_only=True) email=serializers.EmailField(max_length=155,min_length=3,required=True) name=serializers.CharField(max_length=55,min_length=3,required=True) class Meta: model = DoctorProfile fields = ("name", "email", "password", "mobile","otp") class ClinicSerializer(serializers.ModelSerializer): class Meta: model = Doctor_clinic fields =('clinic_name','clinic_address', 'City', 'state', 'pincode','doc_profile') class ClinicRegistrationView(generics.ListCreateAPIView): serializer_class = ClinicSerializer queryset = Doctor_clinic.objects.all() permission_classes = (IsAuthenticated,) -
Getting error "TypeError: Object type <class 'str'> cannot be passed to C code"
I'm following a tutorial on https://medium.com/@nipun.357/aes-encryption-decryption-java-python-6e9f261c24d6 for encryption and decryption in python. I'm getting error in my case: raise TypeError("Object type %s cannot be passed to C code" % type(data)) TypeError: Object type <class 'str'> cannot be passed to C code The code is coverting string to bytes then Why am I getting this error. Why code is not working and how can I reesolve this import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES def get_private_key(secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: s[0:-ord(s[-1:])] iv = Random.new().read(AES.block_size) # Random IV return hashlib.pbkdf2_hmac('SHA256', secret_key.encode(), salt.encode(), 65536, 32) def encrypt_with_AES(message, secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: s[0:-ord(s[-1:])] iv = Random.new().read(AES.block_size) # Random IV private_key = get_private_key(secret_key, salt) message = pad(message) cipher = AES.new(private_key, AES.MODE_CBC, iv) cipher_bytes = base64.b64encode(iv + cipher.encrypt(message)) return bytes.decode(cipher_bytes) def decrypt_with_AES(encoded, secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: …