Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import by fileName is not supportted
I have a django project and a dump.json file in which all the database dump is present. I am trying to run this command to load data into my django project django-admin loaddata dumpdata.json --settings=~/Workspace/odx-lm/lm/settings/local.py On running the above command from the folder ~/Workspace/odx-lm/, I am getting the following error: Traceback (most recent call last): File "/home/delhivery/Workspace/odx-lm/odx-lm-env/bin/django-admin.py", line 5, in management.execute_from_command_line() File "/home/delhivery/Workspace/odx-lm/odx-lm-env/local/lib/python2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/delhivery/Workspace/odx-lm/odx-lm-env/local/lib/python2.7/site-packages/django/core/management/init.py", line 316, in execute settings.INSTALLED_APPS File "/home/delhivery/Workspace/odx-lm/odx-lm-env/local/lib/python2.7/site-packages/django/conf/init.py", line 53, in getattr self._setup(name) File "/home/delhivery/Workspace/odx-lm/odx-lm-env/local/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/delhivery/Workspace/odx-lm/odx-lm-env/local/lib/python2.7/site-packages/django/conf/init.py", line 97, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: Import by filename is not supported. Any help would be highly appreciated. -
how to make tooltip visible before slide in jquery ui slider multiple handles
while sliding the handle iam getting tooltip with ui.value but before slide iam not getting tooltip, i want to make tooltip with current date always visible to user, please help. $(function () { var slider_min_date = '{{slider_min_date}}'; var slider_max_date = '{{slider_max_date}}'; var slider_value_list = []; {% for obj in slider_list %} //slider_list is list of date obj slider_value_list.push(new Date('{{obj}}').getTime() / 1000); {% endfor %} var tooltips = function( event, ui ) { var curValue = $(this).index(); var tooltip = $('<div class="ui-slider-tooltip" />'); //$(event.target).find('.ui-slider-handle').append(tooltip); $('.ui-slider-handle').html(tooltip); }; var slider = $("#slider-id").slider({ range: false, min: new Date(slider_min_date).getTime() / 1000, max: new Date(slider_max_date).getTime() / 1000, step: 86400, //seconds per day values: slider_value_list, create: tooltips, tooltip:true, start: function( event, ui ) { $(ui.handle).find('.ui-slider-tooltip').show(); }, stop: function( event, ui ) { $(ui.handle).find('.ui-slider-tooltip').show(); }, slide: function(event, ui) { var han_val =new Date(ui.value *1000).toDateString(); $(ui.handle).find('.ui-slider-tooltip').text(han_val); }, }) }); -
Simple Password Confirmation using Django Forms (v1.10)
I need to implement a very simple password confirmation in Django that will allow the user to enter a value in an input field. Template <form class="form-inline" method="POST" action="{% url 'details' %}"> {% csrf_token %} {{ form.tact_password }} {{ form.tacttime }} <br> <button type="submit" class="btn btn-outline-primary" value="submit">Submit </button> </form> Forms.py from django import forms class TactForm(forms.Form): tact_password = forms.CharField(widget=forms.PasswordInput( attrs = { 'class' : 'form-control mb-2 mr-sm-2 mb-sm-0', 'placeholder' : 'Enter Password:', 'id' : 'inlineFormInput' } ),label='Tact Password', max_length=100) Let's say my predefined password is HelloWorld, and I would like the user to be able to submit the form if his password matches HelloWorld. Many questions I found like this, involve checking two different input fields and seeing if they match, which is a different scenario. Can a similar method be used or is there a more efficient way? -
After Upgrade to Django 2.1 500 error messages are not sent anymore
Since I upgraded my site to Django 2.1 the error emails with the 500 information are not sent anymore. I did not change the settings in anyway. They look like this (excerpt from diffsettings) SERVER_EMAIL = 'bla@example.com' ### LOGGING = {} ### LOGGING_CONFIG = 'logging.config.dictConfig' ADMINS = [('Admin', 'admin@example.com')] ### DEBUG = False As you can see i have the default logging config, and debug is set to false. I also tested my email settings and when i manually send an email(with the server email address as sender and the admin email address as receiver everything works fine. I did not fin anything that this is a known bug in Django 2.1 -
I am getting __init__() got an unexpected keyword argument 'instance' with CreateView
I am using Django 2.1 version. I am trying to make CreateView. Here is my views.py; # views.py class CreateJob(CreateView): form_class = CreateJob template_name = 'category_list.html' and here is my forms.py; # forms.py from django import forms from myapp.models import Category class CreateJob(forms.Form): CATEGORY_CHOICES = ( ) category_list = forms.ChoiceField( widget=forms.Select(attrs={ "id": "cate" }), choices=CATEGORY_CHOICES, required=True, ) def __init__(self, *args, **kwargs): super(CreateJob, self).__init__(*args, **kwargs) category_choices = [(cat.id, cat.name) for cat in Category.objects.all()] self.fields['category_list'].choices = category_choices in this forms.py I am trying to make choicefield and list category objects. and in my template, when i select category, it will make ajax request and will list description list which is related to Category model. you can look my template below. once I select one of categories which is created via choicefield in forms.py, it will list description list in option which has "desc" id. {% extends '../base.html' %} {% block body %} <form action="." method="post"> {% csrf_token %} {{ form }} </form> <select id="desc"> {% for description in description_list %} <option value="{{ description.pk }}">{{ description.name }}></option> {% endfor %} </select> {% endblock %} {% block script %} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function (e) { $("#cate").change(function(e) { cat = $(this).val(); var job = $("#desc"); β¦ -
Django Map request body to Model
Hey guys is it possible to to see what a model/serialzer a request matches. For instance if my body is sends: ` project_id: 1, title: "Hello", message: "World" ` To run some code like matchingModel = AllMyModels.map(request.body) And have matchingModel be something like Project -
Generating ZipFile with Django from already defined classes
I have 2 defined classes in my views that generate CSV files. I want to give the option of downloading both files at once in a zip file or each individually. I've created this class in my views to generate my ZIP class ExportPBI(LoginRequiredMixin, ListView): file1 = ExportInitiativeAssessmentsView.as_view() # Class defined above and returned a csv file file2 = ExportRegistryAssessmentsView().as_view() # Class defined above and returned a csv file current_files = [file1, file2,] zipped_file = StringIO.StringIO() with zipfile.ZipFile(zipped_file, 'w') as zip: for file in current_files: zip.write('Initiative-Export.csv') zipped_file.close() -
Django:How to upload,display,delete images by admin
I'm learning django now.I would like to display some pictures in front end,however, I want to upload,delete and update pictures by admin instead of writing code in front end. I've finished some codes.I don't know how to do next. Here's my code: settings: MEDIA_ROOT = os.path.join(BASE_DIR,'static/images/bxslider/') MEDIA_URL = '/images/bxslider/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) models: class BxSlider(models.Model): status_choice = ( (0,'online'), (1,'offline'), ) status = models.IntegerField(choices=status_choice,default=1) name = models.CharField(max_length=32) img = models.ImageField(upload_to='') herf = models.CharField(max_length=256) create_date = models.DateTimeField(auto_now_add=True,editable=True) update_date = models.DateTimeField(auto_now=True,null=True) class Meta: db_table = 'BxSlider' verbose_name_plural = 'index slider' def __str__(self): return self.name views: def index(request): #addr = models.BxSlider.objects.get() #I don't know how to write this return render(request,'index.html',{"addr":addr}) index.html: <div class="bxslider"> <div><img src="" style="width:100%;"></div> <!-- I don't know how to write,so I can call pictures from admin --> </div> -
Django: ForeignKey and related_name
Please help me to write model with ForeignKeys. Table 1: | ports | CREATE TABLE `ports` ( `id` int(11) NOT NULL AUTO_INCREMENT, `device_id` int(11) DEFAULT NULL, `name` int(10) DEFAULT NULL, `login` varchar(255) DEFAULT NULL, `state` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `device_id` (`device_id`), KEY `name` (`name`), KEY `state` (`state`), KEY `login` (`login`), CONSTRAINT `ports_ibfk_1` FOREIGN KEY (`device_id`) REFERENCES `switch` (`id`) ON DELETE CASCADE ) Model for table 1: class Ports(models.Model): device_id = models.ForeignKey('Switch', models.DO_NOTHING, blank=True, null=True) name = models.IntegerField(blank=True, null=True) login = models.CharField(max_length=255, blank=True, null=True) state = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'ports' Table 2: | switch | CREATE TABLE `switch` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '', `addr` varchar(255) NOT NULL DEFAULT '', `community` varchar(255) NOT NULL DEFAULT '', `type` int(11) DEFAULT NULL, `ports` int(11) DEFAULT NULL, `street_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `type` (`type`), CONSTRAINT `switch_ibfk_1` FOREIGN KEY (`type`) REFERENCES `switch_types` (`id`) ) Model for table 2: class Switch(models.Model): name = models.CharField(max_length=255) addr = models.CharField(max_length=255) community = models.CharField(max_length=255) type = models.ForeignKey('SwitchTypes', models.DO_NOTHING, db_column='type', blank=True, null=True) ports = models.IntegerField(blank=True, null=True) street_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'switch' When i run the server β¦ -
Cloud Text Editor
I am relatively new for world of web-based-coding and I got a long-term project to build a software which is a web-based text editor. Later, this software will use a db that will be built and used to be read and stored to. I looked some guides to build such software but lack of clues. Preferably, I want to use powerful (or at least a good start for learning web service) frameworks for front-end and back-end (if this is needed). I've looked for Angular , Symfony , and Django. I'm looking for a suggestion or critics or advices, where should I start from, in order to build this software. I appreciate for the help. Thank you very much. -
subquery in WHERE clause with inverted Q object
I have two models, where one refers to another: class A(models.Model): variable = models.BooleanField(default=False, null=False) b = models.ForeignKey(B, on_delete=models.CASCADE, related_name='as', related_query_name="a") class B(models.Model): pass I would like to follow backward the relation while filtering on variable: B.objects.filter(~Q(a__variable)) Problem: This yields an extra subquery in the where clause: 'SELECT "b"."id" FROM "b" WHERE NOT ("b"."id" IN (SELECT U1."b_id" FROM "a" U1 WHERE U1."variable" = True))' On the other hand, when not inverting the Q expression B.objects.filter(Q(a__variable)) the join is done "correctly", i.e. outside the where clause: 'SELECT "b"."id" FROM "b" INNER JOIN "a" ON ("b"."id" = "a"."b_id") WHERE "a"."variable" = True' I'm using django 2.0.4 and postgres 9.6.2 -
html dot interacting with django admin
my html code doesnt seem to be interacting with my django admin after making use of jinja logic in my code, here's a piece of my code {% for Second in Second %} <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-8"> <h2 class="featurette-heading">{{ Second.title }}</h2> <p class="lead">{{ Second.body }}</p> </div> <div class="col-md-4"> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" src="{{ Second.pics.url}}" alt="Generic placeholder image" width="400" height="300"> </div> </div> </hr> {% endfor %} and my models is thus class Second(models.Model): title= models.CharField(max_length=500) body= models.TextField() pics= models.ImageField(upload_to='profile_image/%Y/%m/%d', blank=True) dateone = models.DateTimeField() def __str__(self): return self.title -
Populate a form with the user detail after submitting he form to the admin
I'm working on leave management system where a user submits this form - from django import forms from lrequests.models import Leave class LeaveRequestForm(forms.ModelForm): class Meta: fields = ("department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason") model = Leave whose model is - from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) department = models.CharField(max_length = 50) designation = models.CharField(max_length = 50) type_of_leave = models.CharField(max_length = 15, choices = CHOICES) from_date = models.DateField(help_text = 'mm/dd/yy') to_date = models.DateField(help_text = 'mm/dd/yy') reporting_manager = models.CharField(max_length = 50, default = None, help_text = '0001_manager, 0002_manager') reason = models.CharField(max_length= 180) status = models.IntegerField(choices=STATUS_CHOICES, blank=True, null=True) reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True) def __str__(self): return self.name The user doesn't fill the fields name and employee_ID, which were given at the time of signing up. These should automatically get filled in the admin site and db. I've tried and read documentation on ModelAdmin.prepopulated_fields but couldn't come to the point. Can anyone please explain this topic in detail, am I heading in the correct direction or not? -
Django form doesn't assign foreign key attribute for subclass
I have this model structure in Django(ommited irrelevant class fields): models.py class Policy(models.Model): POLICY_TYPE_CHOICES = ( (1, 'komunikacja'), (2, 'majΔ tek') ) policy_type = models.IntegerField( choices = POLICY_TYPE_CHOICES, default = 1, ) class MotorPolicy(Policy): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) class PropertyPolicy(Policy): property = models.CharField(max_length=100) views.py class PolicyCreateTransitionView(generic.TemplateView): template_name = 'helper/policy_transition.html' class PropertyPolicyCreate(generic.CreateView): form_class = PropertyPolicyForm template_name = 'helper/policy_form.html' class MotorPolicyCreate(generic.CreateView): form_class = MotorPolicyForm template_name = 'helper/policy_form.html' In my template I'm loading via ajax contents of a form, depending on user choice. ajax_policy_type.js function load() { var option = $("input:radio[name=policy_type]:checked").val(); if(option === "vehicle") { $('#form').load("newmotorpolicy/ #content", postLoadMotor); } if(option === "property") { $('#form').load("newpropertypolicy/ #content", postLoadProperty); } function postLoadMotor() { $.datepicker.setDefaults($.datepicker.regional['pl']); $( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }); console.log("Pickers prepared"); } function postLoadProperty() { $.datepicker.setDefaults($.datepicker.regional['pl']); $( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }); console.log("Pickers prepared"); $('#form_new_policy').attr('action', 'newpropertypolicy/'); console.log("Form post action changed") } policy_form.html {% block content %} <form id="form_new_policy"action="newmotorpolicy/" method="POST" enctype="multipart/form-data">{% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Zapisz" /> {{ form.media }} </form> {% endblock %} forms.py class PropertyPolicyForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__() self.fields['policy_type'].initial = 2 class Meta: model = PropertyPolicy class MotorPolicyForm(ModelForm): class Meta: model = MotorPolicy When I submit the form, it creates a Policy of the correct subclass, but β¦ -
Get URL pk in django forms.py
I have this URL path('private/productores/<pk>', views.Productor_Private.as_view()), Views.py class Productor_Private(generic.DetailView): model = Productor template_name = 'firstpage/productor_private.html' def get(self, request, pk): form = RepartoForm() return render(request, self.template_name, {'form': form}) def post(self, request, pk): form = RepartoForm(request.POST) if form.is_valid(): return render(request, self.template_name, args) I want to retrieve the pk from the URL to use it as a filter inside the forms.py, to do something like this: class RepartoForm(forms.Form): productos = forms.ModelMultipleChoiceField(queryset=Producto.objects.filter(productor=pk)) So in other words, I need to check what the current user's "productor" id is in order to only retrieve the "productos" that belong to this "productor" -
Django - removing records and files from application by 'DELETE' method
I have the following problem with my project in django 2.0.3. My application is based on the following model: models.py from django.db import models from django.contrib.auth.models import User class InputSignal(models.Model): name = models.CharField(max_length=512) author = models.ForeignKey(User, on_delete=models.CASCADE) adnotations = models.TextField(blank=True, null=True) input_file = models.FileField(upload_to='signals/', null=True) objects = models.Manager() def __str__(self): return self.name I wanted to develop a mechanism to display rows contained in this database, and to delete individual records by 'DELETE' method. That's why I created this view function: views.py def storage_list(request): signals = InputSignal.objects.filter(author=request.user) if request.method == 'DELETE': id = json.loads(request.body)['id'] signal = get_object_or_404(InputSignal, id=id) signal.delete() return HttpResponse('') else: return render(request, 'storage_list.html', {'signals': signals}) and following template: storage.html <ul> {% for signal in signals %} <li> <div class="row"> <h1>{{ signal.name }}</h1> </div> <div class="row"> <h6>Adnotations:</h6> </div> <div class="row"> <p>{{ signal.adnotations | safe | linebreaks | truncatewords:16 }}</p> </div> <div class="row"> <button data-id="{{ signal.id }}" onclick='delteSignal(this)' class="btn btn-danger">Delete</button> </div> <hr> </li> {% endfor %} </ul> Which uses this js. script: script.js function delteSignal(e){ let id = e.dataset.id e.closest('li').remove() fetch('', { method: 'DELETE', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'id': id }), credentials: 'same-origin', }) } As a result of the operation of the presented code, the β¦ -
PYMQI return data type issue
I am trying the get IBM MQ Messages out of Queue Manager by reading the queue "SYSTEM.ADMIN.COMMAND.EVENT". I am getting the following response when I print the message. How do I convert the following message into a user friendly format after reading the queue: b'\x00\x00\x00\x07\x00\x00\x00$\x00\x00\x00\x03\x00\x00\x00c\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\tm\x00\x00\x00\x02\x00\x00\x00\x14\x00\x00\x00\x10\x00\x00\x1fA\x00\x00\x00\t\x00\x00\x00\x04\x00\x00\x00 \x00\x00\x0b\xe5\x00\x00\x033\x00\x00\x00\x0cnb153796 \x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xf3\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00D\x00\x00\x0b\xe7\x00\x00\x033\x00\x00\x000ZANC000.YODA \x00\x00\x00\t\x00\x00\x000\x00\x00\x1bY\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x004\x00\x00\x0b\xe9\x00\x00\x033\x00\x00\x00 \x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xf2\x00\x00\x00\x1c\x00\x00\x00\x04\x00\x00\x000\x00\x00\x0b\xea\x00\x00\x033\x00\x00\x00\x1cMQ Explorer 9.0.0 \x00\x00\x00\x04\x00\x00\x00\x18\x00\x00\x0b\xeb\x00\x00\x033\x00\x00\x00\x04 \x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xfd\x00\x00\x00\xa1\x00\x00\x00\x14\x00\x00\x00\x10\x00\x00\x1fB\x00\x00\x00\x01\x00\x00\x00\x05\x00\x00\x00\x14\x00\x00\x04\xcd\x00\x00\x00\x01\x00\x00\x03\xf1' My code is as follows, I am using Python 3.6 and Django 2.1 everything is working fine except the format or the returned message: Please assist infiguring out how to convert the returned message from PYMQI Queue Get # from django.shortcuts import render from django.http import HttpResponse import pymqi # queue_manager = "QueueManager" channel = "Channel" host = "hostname" port = "port" queue_name = "SYSTEM.ADMIN.COMMAND.EVENT" user = "username" password = "password" connection_info = "%s(%s)" % (host, port) # #(option, args) = OptionParser # Create your views here. def index(request): # qmgr = pymqi.connect(queue_manager, channel, connection_info, user, password) # queue = pymqi.Queue(qmgr, queue_name) print(queue.get()) messages = queue.get() #for message in messages: # print(type(message)) queue.close() qmgr.disconnect() return HttpResponse("MQ Hello Tests %s" % messages.hex()) -
How to index `bulk_create`d objects in django, haystack?
Django's bulk_create doesn't raise post_save signal and haystack's RealtimeSignalProcessor listens to post_save signal of an object. I'm running bulk_create in the background using django-rq. Is there a neat way to index bulk_created objects without reindexing everything from rqscheduler's cron job? -
Can't upload media files django on digital ocean
I've recently deployed a django app on digital ocean. Everything works perfectly fine until I try to create an object containing an image. I get an error saying Server Error (500). Here is what I've tried to do : server { listen 80; server_name ****; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/joseph/hacka; } location /media/ { root /home/joseph/hacka; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Unfortunately, that hasn't work out. Please help me if you know the anwer to my problem. -
A way to disable @login_required
We have our own login decorator and we want to disable the default @login_required so anyone who will import and use the original decorator will get an exception. How can we money-patch / disable this function? Thank you -
Nested serializers saving
I am trying to create a nested serializer to be able to save from parent POST the childs as well. I have the following model: class Parent: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) class Child: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) parent = models.ForeignKey( 'Parent', null=True, on_delete=models.PROTECT, related_name='child_list') And following serializer: class ParentSerializer(serializers.ModelSerializer): child_list = RuleSerializer(many=True, read_only=True) class Meta: model = Parent fields = ('id', 'name', 'child_list') def create(self, validated_data): print(validated_data) rules_data = validated_data.pop('rule_list') parent = Parent.objects.create(**validated_data) for rule_data in rules_data: Child.create(**rule_data) return parent But when i am posting i get error KeyError at /parent/ 'child_list' Do i miss something ? -
How to get lat and long from the data stored in my django database?
I have a full list of data of hotel's address, but i want latitude and longitude from the address each time the users enter the input fields. and then display them a map of hotels in that specific loactions... -
Building a geographical location filter app in Django
I would like to create a market place like app with Djano as the backend server, where users can buy/sell items. In the app I would like have to a feature related to geographic region of a user. Such as, to filter out items in a given specific miles of radius. Example use case: User uploads an item, get the gps cordinates from their mobile and store in db. User can search item, also filter to only get items in X miles radius. For this feature I have looked at GeoDjango. But it seems like I need to extend the postgresql database to use it, also by using the postgis engine. I have also looked at the Haversine formula for nearby queries. There is also an option for multiple database support. But I have some initial doubts before proceeding and your insights would really help me alot. Could you please help me with this queries: I will have to store user data and some other data including the geo location. Will there be any difference/side effects between postgresql_psycopg2 and postgis, to store all the data in one single db? For my simple use case would you rather prefer to go β¦ -
python django mysqlclient error
when i run ' python -m pip install -r requirements.txt' i got these error Looking in indexes: http://mirrors.aliyun.com/pypi/simple/ Requirement already satisfied: Django==2.1 in /usr/local/lib64/python3.6/site-packages (from -r requirements.txt (line 1)) (2.1) Requirement already satisfied: django-cors-headers==2.4.0 in /usr/local/lib/python3.6/site-packages (from -r requirements.txt (line 2)) (2.4.0) Collecting mysqlclient==1.3.13 (from -r requirements.txt (line 3)) Downloading http://mirrors.aliyun.com/pypi/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz (90kB) 100% |ββββββββββββββββββββββββββββββββ| 92kB 1.6MB/s Complete output from command python setup.py egg_info: /bin/sh: mysql_config: ζͺζΎε°ε½δ»€ Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-gwk75e0z/mysqlclient/setup.py", line 18, in <module> metadata, options = get_config() File "/tmp/pip-install-gwk75e0z/mysqlclient/setup_posix.py", line 53, in get_config libs = mysql_config("libs_r") File "/tmp/pip-install-gwk75e0z/mysqlclient/setup_posix.py", line 28, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-gwk75e0z/mysqlclient/ what should i do to resolve -
List Serializer multiple object creation
My Models class User(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField() class Lawyer(models.Model): user = models.OnetoOneField(User) class Session(models.Model): name = models.CharField() lawyer = models.ForeignKey(Lawyer) I am trying to create multiple objects with a list serializer for Session table, From the appside they don't have the id of lawyer but has the email of each lawyer. How can I write a listserializer where I can take the following json input and use email to fetch lawyer to store multiple session objects? The json input sent will be like [ { "name": "sess1", "email": "lawyer1@gmail.com", }, { "name": "sess1", "email": "lawyer1@gmail.com", }, ]